diff --git a/.codeclimate.yml b/.codeclimate.yml deleted file mode 100644 index 164135dd2de..00000000000 --- a/.codeclimate.yml +++ /dev/null @@ -1,6 +0,0 @@ -version: "2" -plugins: - sonar-java: - enabled: true - config: - sonar.java.source: 8 \ No newline at end of file diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index d171944d877..00000000000 --- a/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -./* -!docker-entrypoint.sh - diff --git a/.github/scripts/check_math_usage.sh b/.github/scripts/check_math_usage.sh new file mode 100755 index 00000000000..405d1d850d0 --- /dev/null +++ b/.github/scripts/check_math_usage.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Prints every Java file that uses java.lang.Math: bare `Math.` calls, fully +# qualified `java.lang.Math.` calls (including static imports) and +# `import java.lang.Math`. No output means no forbidden usage. +# StrictMathWrapper.java and MathWrapper.java are exempt. String literals, char +# literals and comments are stripped before matching, so `StrictMath.` and +# mentions in text are not reported. +# Used by .github/workflows/math-check.yml; run it locally from any directory. +set -euo pipefail + +cd "$(dirname "$0")/../.." + +find . -type f -name '*.java' -not -path '*/build/*' | while IFS= read -r file; do + case "$(basename "$file")" in + StrictMathWrapper.java|MathWrapper.java) continue ;; + esac + + 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 - + + bash .github/scripts/check_math_usage.sh > math_usage.txt + if [ -s math_usage.txt ]; then echo "❌ Error: Forbidden Math usage found in the following files:" cat math_usage.txt diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000000..3d10490a36a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,184 @@ +# AGENTS.md + +Guidance for AI coding assistants and new contributors working on java-tron: how to build, test, and navigate the codebase, plus the constraints that CI enforces and the invariants that must not be broken. For running a node, see the [README](./README.md) and [`docs/`](./docs). + +## Guidelines + +- **Keep changes minimal and focused.** Only modify code directly related to the task at hand. Do not refactor unrelated code, rename existing variables or functions for style, or bundle unrelated fixes into the same commit or PR. +- **Do not add, remove, or update dependencies** unless the task explicitly requires it. Dependency changes in a consensus node are high-risk, need separate review, and require regenerating dependency verification metadata (see checklist step 6). +- **Never hand-edit generated sources.** Protobuf / gRPC Java stubs are generated at build time from `protocol/src/main/protos/` (`core/`, `api/`) and are git-ignored. Rebuild after changing a `.proto`. + +## Build & Test + +Supported platforms: **Linux** and **macOS** only. The JDK requirement is determined by CPU architecture: **JDK 8** on x86_64, **JDK 17** on ARM64/aarch64 (Apple Silicon, AWS Graviton). The build fails fast if the JDK major version does not match the architecture. + +```bash +./gradlew clean build -x test # build without tests +./gradlew build # build with tests +./gradlew test # run all tests +./gradlew :framework:test # test one module +./gradlew :framework:test --tests "org.tron.core.db.TronDatabaseTest" # one class +./gradlew :framework:test --tests "org.tron.core.db.TronDatabaseTest.TestGetUnchecked" # one method +./gradlew :framework:testWithRocksDb # RocksDB tests (x86 only) +./gradlew jacocoTestReport # coverage report +``` + +- Main entry point: `org.tron.program.FullNode`. +- Tests also run in parallel in CI: `framework/build.gradle` sets `maxParallelForks` without checking the `CI` env var. Each module configures its own test parallelism in its `build.gradle`. +- On ARM64/aarch64, only the RocksDB storage engine is supported; the build forces RocksDB and skips the LevelDB tests. +- CI builds the full matrix: **JDK 8 / x86_64** (rockylinux, debian11) and **JDK 17 / aarch64** (macOS, ubuntu24). A change must compile on both. + +## Pre-Commit Checklist + +Run **all** applicable checks before committing. Each maps to a CI job that will otherwise fail the PR. + +### 1. Build + +```bash +./gradlew clean build -x test +``` + +### 2. Tests + +```bash +./gradlew test +``` + +### 3. Checkstyle + +Run exactly what CI runs (`.github/workflows/pr-check.yml`): + +```bash +./gradlew :framework:checkstyleMain :framework:checkstyleTest :plugins:checkstyleMain +``` + +CI runs Checkstyle only for `framework` and `plugins`; `protocol` is checked by `protoLint` instead (see Protobuf below). `p2p` has its own Checkstyle configuration (`./gradlew :p2p:checkstyleMain :p2p:checkstyleTest`) that is not part of the CI gate. A bare `./gradlew checkstyleMain` does not reproduce the CI gate. + +### 4. Forbidden `Math` usage + +CI (`.github/workflows/math-check.yml`) **fails the build on any use of `java.lang.Math`** anywhere in the repository: bare `Math.` calls, fully qualified `java.lang.Math.` calls (including static imports), and `import java.lang.Math`. Only `StrictMathWrapper.java` and `MathWrapper.java` are exempt. + +Use `org.tron.common.math.StrictMathWrapper` instead. Self-check before pushing with the script CI runs (`StrictMath.` and occurrences in strings or comments are ignored): + +```bash +bash .github/scripts/check_math_usage.sh +``` + +No output means the gate passes. + +This exists because `java.lang.Math` gives platform-dependent results for floating-point operations, which breaks cross-JVM determinism between the x86/JDK 8 and ARM64/JDK 17 builds. + +### 5. Config validation — only if you touched `reference.conf` + +```bash +pip install -r .github/scripts/requirements.txt # pyhocon, required by the first script +python3 .github/scripts/check_reference_conf.py common/src/main/resources/reference.conf +python3 .github/scripts/check_reference_comments.py common/src/main/resources/reference.conf +``` + +Both gates run in CI. The rules: + +- Every key path segment must match `^[a-z][a-zA-Z0-9]*$` (only the first character is constrained; acronyms such as `httpPBFTEnable` are fine). This is what `ConfigBeanFactory` bean-binding requires. +- Total path depth ≤ **5**; each list/array step counts as one level. +- Service-binding port values (leaf named `port` or ending in `Port`, outside arrays) must be unique; `0` and `-1` are reserved sentinels. +- **Every key needs a comment** — inline on the same line, or on the immediately preceding line. Blank lines do not count. + +See [`docs/configuration-conventions.md`](./docs/configuration-conventions.md). + +### 6. Dependency verification — only if you touched dependencies + +`gradle/verification-metadata.xml` pins checksums for every resolved artifact (`verify-metadata=true`). Adding, removing, or upgrading any dependency requires regenerating it, or the build fails for everyone: + +```bash +./gradlew --write-verification-metadata sha256 help +``` + +Review the resulting diff — it must contain only the artifacts your change actually introduces. + +### 7. Do not commit binaries + +No `*.jar`, `build/`, logs, or database files — whether produced by the main build or as byproducts of investigation. + +## Module Layout + +| Module | Responsibility | +|--------|----------------| +| `framework` | Main entry (`org.tron.program.FullNode`); wires all modules; largest test suite | +| `protocol` | Protobuf / gRPC definitions | +| `chainbase` | Blockchain storage abstraction (LevelDB / RocksDB); snapshot & rollback | +| `consensus` | Pluggable DPoS consensus engine | +| `actuator` | Transaction execution; one Actuator class per transaction type | +| `crypto` | Cryptographic primitives (depends only on `common`) | +| `common` | Shared utilities | +| `p2p` | Peer discovery, connection management and DNS-based node lists; vendored from [tronprotocol/libp2p](https://github.com/tronprotocol/libp2p) (see [`p2p/README.md`](./p2p/README.md)) | +| `platform` | Architecture-specific implementations selected at build time (separate `x86` / `arm` / `common` source sets): math wrappers, LevelDB/RocksDB order-price comparators — relevant to cross-JVM determinism | +| `plugins` | Standalone tools (`Toolkit.jar`, `ArchiveManifest.jar`) | + +`errorprone` and `example:actuator-example` are build-support and sample modules, not part of the node. + +**Module dependency direction is one-way — do not introduce reverse dependencies:** + +```text +framework → chainbase → common → protocol +actuator → chainbase +consensus → chainbase / common (only via ConsensusDelegate; never call Manager directly) +crypto → common +``` + +`platform` is a leaf module (no project dependencies of its own) that `common`, `framework`, and `plugins` depend on for architecture-specific code. + +`p2p` is also a leaf module. + +## Hard Constraints + +**Cross-JVM determinism** (consensus, state transition, block ordering) — the same block must produce the same state on every supported platform: +- Never use `java.lang.Math` — use `org.tron.common.math.StrictMathWrapper` instead (CI-enforced, see checklist step 4). +- Never use `float` / `double` in consensus-relevant arithmetic. +- Never depend on `HashMap` iteration order for a business decision. +- Use the DPoS slot time for produced-block timestamps, not `System.currentTimeMillis()`. +- Never call `String.toLowerCase()` / `toUpperCase()` without an explicit `Locale` — ErrorProne enforces this as a compile error (`StringCaseLocaleUsage`). + +**DB / Store:** +- All writes must happen inside a revocable session — `try (ISession session = revokingStore.buildSession())` — never a bare `put()`. +- A new store must extend `TronStoreWithRevoking` and register with the `RevokingDatabase`. +- Multi-store updates must roll back fully on exception. + +**Actuator:** +- New actuators are registered automatically: place the class in the `org.tron.core.actuator` package, extend `AbstractActuator`, and pass the `ContractType` to `super(...)` from a no-arg constructor. `TransactionRegister.registerActuator()` discovers it by reflection at startup — there is no manual registration step. +- `validate()` must check that the owner can afford `calcFee()` plus any amount being moved; the fee itself is charged inside `execute()` together with the state change, so a failed `execute()` rolls back both. Bandwidth, multi-signature and memo fees are charged by `Manager.processTransaction()` before the actuator runs — an actuator never touches them. +- `validate()` must not mutate state. + +**Protobuf:** +- Fields may only be added — never removed or renumbered. +- Message field numbers start at `1`; the first enum value must be `0`. +- In a new enum, the zero value's name must start with `UNKNOWN_` (e.g. `UNKNOWN_STATUS = 0;`, not `SUCCESS = 0;`). `protocol/protoLint.gradle` enforces this during `./gradlew build`; only the existing enums in its `legacyEnums` whitelist are exempt. + +**API / Threads:** +- New HTTP servlets must go through `HttpApiAccessFilter` and use `Wallet` (never inject `Manager` directly). +- A new gRPC or HTTP query that depends on historical data (unavailable on a lite fullnode) must be added to the deny-list in `LiteFnQueryGrpcInterceptor` / `LiteFnQueryHttpFilter`; other methods need no action — the interceptor and filter are installed server-wide. +- No bare `new Thread()` — use a named Executor, shut down via `shutdown()` → `awaitTermination()` → `shutdownNow()`. + +## Common Pitfalls + +1. **ErrorProne only runs on JDK 11+.** Building on x86/JDK 8 will *not* surface `StringCaseLocaleUsage` violations, but the aarch64/JDK 17 CI jobs will fail. If you only build on x86, you will not see these locally. +2. **`./gradlew checkstyleMain` is not the CI gate.** Use the exact module-scoped command in checklist step 3. +3. **Adding a config key without a comment fails CI**, even if the key itself is valid. +4. **Changing a dependency without regenerating `verification-metadata.xml` breaks the build for everyone**, not just you. +5. **Generated protobuf sources are git-ignored.** If a build error references a missing generated class, rebuild instead of creating the file. +6. **Consensus-affecting behaviour changes need a proposal / fork gate**, not just a code change. Changing how an existing transaction validates or executes will fork the network unless gated. When in doubt, ask before implementing. + +## Authoritative Documentation + +- **Build / run / node operation:** [README](./README.md) +- **Configuration:** [`docs/configuration.md`](./docs/configuration.md), [`docs/configuration-conventions.md`](./docs/configuration-conventions.md) +- **Protobuf protocol:** the `.proto` files under `protocol/src/main/protos/` are the source of truth; [`docs/protobuf-protocol-document.md`](./docs/protobuf-protocol-document.md) explains the main messages (the Markdown copies under `protocol/src/main/protos/` are outdated). +- **Extending / deployment:** the [`docs/`](./docs) directory (customized actuator, modular deployment). +- **P2P module:** [`p2p/README.md`](./p2p/README.md) (standalone use, DNS node-list publishing, API). +- **Contributing:** [CONTRIBUTING.md](./CONTRIBUTING.md) (workflow, coding style, commit/PR conventions). +- **Security policy:** [SECURITY.md](./SECURITY.md) (supported versions, vulnerability disclosure). + +## Commit & PR Convention + +Commit messages and PR titles follow `type(scope): description`. The allowed types, the full scope list and the subject rules are defined in [CONTRIBUTING.md](./CONTRIBUTING.md#commit-messages) — follow it there. + +PR titles and descriptions are validated in CI by `.github/workflows/pr-check.yml`. Fill in `.github/PULL_REQUEST_TEMPLATE.md`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef67a81e3ee..0f1844df026 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -147,7 +147,7 @@ We would like all developers to follow a standard development flow and coding st 2. Review the code before submission. 3. Run standardized tests. -`Sonar`-scanner and CI checks (GitHub Actions) will be automatically triggered when a pull request has been submitted. When a PR passes all the checks, the **java-tron** maintainers will then review the PR and offer feedback and modifications when necessary. Once adopted, the PR will be closed and merged into the `develop` branch. +CI checks (GitHub Actions) will be automatically triggered when a pull request has been submitted. When a PR passes all the checks, the **java-tron** maintainers will then review the PR and offer feedback and modifications when necessary. Once adopted, the PR will be closed and merged into the `develop` branch. We are glad to receive your pull requests and will try our best to review them as soon as we can. Any pull request is welcome, even if it is for a typo. @@ -158,7 +158,6 @@ Please do not be discouraged if your pull request is not accepted, as it may be Please make sure your submission meets the following code style: - The code must conform to [Google Code Style](https://google.github.io/styleguide/javaguide.html). -- The code must have passed the Sonar scanner test. - The code has to be pulled from the `develop` branch. - The commit message should start with a verb, whose initial should not be capitalized. - The commit message title should be between 10 and 72 characters in length. diff --git a/README.md b/README.md index edf99c4df92..721468efdd3 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ - [Building the Source Code](#building-the-source-code) - [Executables](#executables) - [Running java-tron](#running-java-tron) +- [Documentation](#documentation) - [Community](#community) - [Contribution](#contribution) - [Resources](#resources) @@ -80,6 +81,7 @@ The java-tron project comes with several runnable artifacts and helper scripts f | :---------------------- | :---------- | | **`FullNode.jar`** | Main TRON node executable (generated in `build/libs/` after a successful build following the above guidance). Runs as a full node by default. `java -jar FullNode.jar --help` for command line options| | **`Toolkit.jar`** | Node management utility (generated in `build/libs/`): partition, prune, copy, convert DBs; shadow-fork tool. [Usage](https://tronprotocol.github.io/documentation-en/using_javatron/toolkit/#toolkit-a-java-tron-node-maintenance-suite) | +| **`p2p-standalone.jar`** | Peer discovery, connection management and DNS-based node lists (generated in `build/libs/`). See the [p2p guide](./p2p/README.md). | | **`start.sh`** | Quick start script (x86_64, JDK 8) to download/build/run `FullNode.jar`. See the tool [guide](./shell.md). | | **`start.sh.simple`** | Quick start script template (ARM64, JDK 17). See usage notes inside the script. | @@ -195,6 +197,24 @@ When exposing any of these APIs to a public interface, ensure the node is protec Public hosted HTTP endpoints for both mainnet and testnet are provided by TronGrid. Please refer to the [TRON Network HTTP Endpoints](https://developers.tron.network/docs/connect-to-the-tron-network#tron-network-http-endpoints) for the latest list. For supported methods and request formats, see the HTTP API reference above. +# Documentation + +More detailed guides live in the [`docs/`](./docs) directory: + +- **Configuration** + - [Configuration Reference](./docs/configuration.md) — full `config.conf` option reference + - [Configuration Conventions](./docs/configuration-conventions.md) +- **Modular architecture & deployment** + - [Modular Introduction](./docs/modular-introduction-en.md) · [中文版](./docs/modular-introduction-zh.md) + - [Modular Deployment](./docs/modular-deployment-en.md) · [中文版](./docs/modular-deployment-zh.md) + - [P2P Module](./p2p/README.md) — peer discovery, connection management and DNS-based node lists +- **Extending java-tron** + - [Implement a Customized Actuator](./docs/implement-a-customized-actuator-en.md) · [中文版](./docs/implement-a-customized-actuator-zh.md) +- **Protocol** + - [TRON Protobuf Protocol Document](./docs/protobuf-protocol-document.md) — guide to the main Protobuf messages; the `.proto` files under [`protocol/src/main/protos`](./protocol/src/main/protos) are the source of truth +- **Observability** + - [Metrics Changelog](./docs/metrics-changelog.md) — Prometheus metric additions, changes, and removals across java-tron releases + # 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. diff --git a/docs/configuration.md b/docs/configuration.md index d021326a15e..6604170c59c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -165,6 +165,10 @@ localwitness = [ # localWitnessAccountAddress = "T..." ``` +> **Security — protect the block-producing key.** A Super Representative's key can produce blocks and control the account's funds. Prefer the encrypted `localwitnesskeystore` over a plaintext `localwitness` key, and: +> - Restrict the key/keystore file so other users on the host cannot read it: `chmod 600 `. +> - **Never commit a config file that contains a real private key to Git** — it stays in the history permanently. Add such files to `.gitignore` and keep the key file **outside** the repository directory. + ### JSON-RPC (Ethereum-compatible, `node.jsonrpc`) ```hocon diff --git a/METRICS_CHANGELOG.md b/docs/metrics-changelog.md similarity index 98% rename from METRICS_CHANGELOG.md rename to docs/metrics-changelog.md index 3c599796d7a..e28cc7393fc 100644 --- a/METRICS_CHANGELOG.md +++ b/docs/metrics-changelog.md @@ -19,7 +19,7 @@ This file tracks Prometheus metric additions, changes, and removals in java-tron **Pre-4.8.2 Baseline** -Snapshot of metrics emitted prior to this changelog. Per-version provenance is not tracked here; consult `git log` on [`common/src/main/java/org/tron/common/prometheus/`](common/src/main/java/org/tron/common/prometheus/) for exact origin of each metric. +Snapshot of metrics emitted prior to this changelog. Per-version provenance is not tracked here; consult `git log` on [`common/src/main/java/org/tron/common/prometheus/`](../common/src/main/java/org/tron/common/prometheus/) for exact origin of each metric. ### Existing Metrics diff --git a/docs/modular-introduction-en.md b/docs/modular-introduction-en.md index 654fbfcf995..d35d4269995 100644 --- a/docs/modular-introduction-en.md +++ b/docs/modular-introduction-en.md @@ -16,7 +16,7 @@ The aim of java-tron modularization is to enable developers to easily build a de ![modular-structure](https://github.com/tronprotocol/java-tron/blob/develop/docs/images/module.png) -A modularized java-tron consists of nine modules: framework, protocol, common, chainbase, consensus, actuator, crypto, plugins and platform. The function of each module is elaborated below. +A modularized java-tron consists of ten modules: framework, protocol, common, p2p, chainbase, consensus, actuator, crypto, plugins and platform. The function of each module is elaborated below. ### framework @@ -33,6 +33,10 @@ A concise and efficient data transfer protocol is essential to a distributed net Common module encapsulates common components and tools for other modules to access. +### p2p + +The p2p module handles peer discovery, connection management and DNS-based node lists: nodes discover each other over UDP and connect over TCP, and a node list can be published as DNS TXT records for other nodes to fetch. The module is vendored from [tronprotocol/libp2p](https://github.com/tronprotocol/libp2p) and depends on no other module of the project. See [p2p/README.md](../p2p/README.md) for standalone use and the API. + ### chainbase Chainbase is a database module. For probabilistic consensus algorithms such as PoW, PoS and DPoS, situations of switching to a new chain, however unlikely, is inevitable. Because of this, chainbase defines an interface standard supporting databases that can roll back. This interface requires databases to have a state rollback mechanism, a checkpoint-based fault tolerant mechanism and so on. diff --git a/docs/modular-introduction-zh.md b/docs/modular-introduction-zh.md index e1a02f6b778..711794d24f3 100644 --- a/docs/modular-introduction-zh.md +++ b/docs/modular-introduction-zh.md @@ -14,7 +14,7 @@ java-tron 模块化的目的是为了帮助开发者方便地构建出特定应 ![modular-structure](https://github.com/tronprotocol/java-tron/blob/develop/docs/images/module.png) -模块化后的 java-tron 目前分为9个模块:framework、protocol、common、chainbase、consensus、actuator、crypto、plugins、platform,下面分别简单介绍一下各个模块的作用。 +模块化后的 java-tron 目前分为10个模块:framework、protocol、common、p2p、chainbase、consensus、actuator、crypto、plugins、platform,下面分别简单介绍一下各个模块的作用。 ### framework @@ -30,6 +30,10 @@ framework 是 java-tron 的核心模块,不仅是整个链的入口模块, common 模块对公共组件和一些工具类进行了封装,以方便其他模块调用。 +### p2p + +p2p 模块负责节点发现、连接管理和基于 DNS 的节点列表:节点之间通过 UDP 相互发现、通过 TCP 建立连接;节点列表还可以发布为 DNS TXT 记录,供其他节点获取。该模块内置自 [tronprotocol/libp2p](https://github.com/tronprotocol/libp2p),不依赖项目中的其他模块。单独运行方式和接口说明见 [p2p/README.md](../p2p/README.md)。 + ### chainbase chainbase 模块是数据库层面的抽象,像 PoW、PoS、DPoS 这类基于概率性的共识算法不可避免的会以一定的概率发生切链,因此 chainbase 定义了一个支持可回退数据库的接口标准,该接口要求数据库实现状态回滚机制、checkpoint容灾机制等。 diff --git a/Tron protobuf protocol document.md b/docs/protobuf-protocol-document.md similarity index 85% rename from Tron protobuf protocol document.md rename to docs/protobuf-protocol-document.md index d8e621ed69a..5178e417857 100644 --- a/Tron protobuf protocol document.md +++ b/docs/protobuf-protocol-document.md @@ -4,6 +4,8 @@ This is the description of Google Protobuf implementation of Tron's protocol. +> The `.proto` files under [`protocol/src/main/protos`](../protocol/src/main/protos) are the source of truth for every message and field. This document explains the main messages. + ## Contents #### [1. Account](#account) @@ -34,7 +36,7 @@ enum AccountType { } ``` -- message `Account` has multiple attributes and 2 nested messages: +- message `Account` has multiple attributes and 4 nested messages: message `Frozen`: @@ -57,6 +59,35 @@ enum AccountType { int64 storage_limit = 6; 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; + } + ``` + + `energy_window_size`: the window, in blocks, over which energy usage recovers; `0` means the default of 24 hours. When `energy_window_optimized` is true, the value is stored multiplied by 1000. + + `delegated_frozenV2_balance_for_energy`: TRX staked by this account under Stake 2.0 whose energy is delegated to other accounts. + + `acquired_delegated_frozenV2_balance_for_energy`: TRX staked by other accounts under Stake 2.0 whose energy is delegated to this account. + + message `FreezeV2`: TRX staked under Stake 2.0 for one resource type. + + ```java + message FreezeV2 { + ResourceCode type = 1; + int64 amount = 2; + } + ``` + + message `UnFreezeV2`: TRX unstaked under Stake 2.0 and waiting to be withdrawn; `unfreeze_expire_time` is when it becomes withdrawable. + + ```java + message UnFreezeV2 { + ResourceCode type = 1; + int64 unfreeze_amount = 3; + int64 unfreeze_expire_time = 4; } ``` @@ -118,6 +149,22 @@ enum AccountType { `latest_consume_free_time`: the latest consume free bandwidth time of this account. + `net_window_size`: the window, in blocks, over which bandwidth usage recovers; `0` means the default of 24 hours. When `net_window_optimized` is true, the value is stored multiplied by 1000. + + `frozenV2`: TRX staked under Stake 2.0, one entry per resource type. + + `unfrozenV2`: TRX unstaked under Stake 2.0 and waiting to be withdrawn, with the time each amount becomes withdrawable. + + `delegated_frozenV2_balance_for_bandwidth`: TRX staked by this account under Stake 2.0 whose bandwidth is delegated to other accounts. + + `acquired_delegated_frozenV2_balance_for_bandwidth`: TRX staked by other accounts under Stake 2.0 whose bandwidth is delegated to this account. + + `old_tron_power`: under the new resource model (`getAllowNewResourceModel`), the voting power recorded from the account's bandwidth and energy stakes. `0` means not recorded yet, so those stakes still count in full; `-1` means they no longer count and only TRON Power stakes give voting power. + + `tron_power`: TRX frozen under Stake 1.0 for TRON Power (voting power only), available under the new resource model. + + `asset_optimized`: true when this account's TRC-10 balances are kept in a separate account-asset store instead of the `asset` / `assetV2` maps. + ```java message Account { message Frozen { @@ -135,6 +182,9 @@ message Account { int64 net_usage = 8; int64 acquired_delegated_frozen_balance_for_bandwidth = 41; int64 delegated_frozen_balance_for_bandwidth = 42; + int64 old_tron_power = 46; + Frozen tron_power = 47; + bool asset_optimized = 60; int64 create_time = 0x09; int64 latest_opration_time = 10; int64 allowance = 0x0B; @@ -153,6 +203,8 @@ message Account { int64 latest_consume_time = 21; int64 latest_consume_free_time = 22; bytes account_id = 23; + int64 net_window_size = 24; + bool net_window_optimized = 25; message AccountResource { int64 energy_usage = 1; Frozen frozen_balance_for_energy = 2; @@ -162,12 +214,29 @@ message Account { int64 storage_limit = 6; 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; + 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; + int64 delegated_frozenV2_balance_for_bandwidth = 36; + int64 acquired_delegated_frozenV2_balance_for_bandwidth = 37; } ``` @@ -385,19 +454,6 @@ Transaction and transaction-related messages. } ``` - - message `TransactionSign` - - `transaction`: transaction data. - - `privateKey`: private key. - - ```java - message TransactionSign { - Transaction transaction = 1; - bytes privateKey = 2; - } - ``` - - message `ResourceReceipt` `energy_usage`: consume yourself account energy. @@ -414,6 +470,8 @@ Transaction and transaction-related messages. `result`: the result of executing transaction. + `energy_penalty_total`: extra energy charged by the dynamic energy model; it is included in `energy_usage_total`. + ```java message ResourceReceipt { int64 energy_usage = 1; @@ -423,6 +481,7 @@ Transaction and transaction-related messages. int64 net_usage = 5; int64 net_fee = 6; Transaction.Result.contractResult result = 7; + int64 energy_penalty_total = 8; } ``` @@ -451,6 +510,8 @@ Transaction and transaction-related messages. `callValueInfo`: Refers to asset transfer information in internal transactions, including trx and trc10. + `extra`: JSON details for some internal transactions, such as the votes cast by a contract, or the amounts staked again per resource by a contract's cancel-all-unstake call when `vm.saveCancelAllUnfreezeV2Details` is enabled. + ```java message InternalTransaction { bytes hash = 1; @@ -463,6 +524,7 @@ Transaction and transaction-related messages. repeated CallValueInfo callValueInfo = 4; bytes note = 5; bool rejected = 6; + string extra = 7; } ``` @@ -505,6 +567,14 @@ Transaction and transaction-related messages. `exchange_id`: `shielded_transaction_fee`: + + `orderId`: ID of the order created by `MarketSellAssetContract`. + + `orderDetails`: orders matched when that order was placed. + + `withdraw_expire_amount`: expired unstaked TRX withdrawn to the balance by this transaction. + + `cancel_unfreezeV2_amount`: for `CancelAllUnfreezeV2Contract`, the unstaked amounts staked again, keyed by resource type. ```java message Result { @@ -528,6 +598,7 @@ Transaction and transaction-related messages. JVM_STACK_OVER_FLOW = 12; UNKNOWN = 13; TRANSFER_FAILED = 14; + INVALID_CODE = 15; } int64 fee = 1; code ret = 2; @@ -541,6 +612,10 @@ Transaction and transaction-related messages. int64 exchange_withdraw_another_amount = 20; int64 exchange_id = 21; int64 shielded_transaction_fee = 22; + bytes orderId = 25; + repeated MarketOrderDetail orderDetails = 26; + int64 withdraw_expire_amount = 27; + map cancel_unfreezeV2_amount = 28; } ``` @@ -657,6 +732,7 @@ Transaction and transaction-related messages. JVM_STACK_OVER_FLOW = 12; UNKNOWN = 13; TRANSFER_FAILED = 14; + INVALID_CODE = 15; } int64 fee = 1; code ret = 2; @@ -670,6 +746,10 @@ Transaction and transaction-related messages. int64 exchange_withdraw_another_amount = 20; int64 exchange_id = 21; int64 shielded_transaction_fee = 22; + bytes orderId = 25; + repeated MarketOrderDetail orderDetails = 26; + int64 withdraw_expire_amount = 27; + map cancel_unfreezeV2_amount = 28; } message raw { @@ -757,6 +837,16 @@ Transaction and transaction-related messages. `shielded_transaction_fee`: the usage fee for shielded transaction. + `orderId`: ID of the order created by `MarketSellAssetContract`. + + `orderDetails`: orders matched when that order was placed. + + `packingFee`: the part of the bandwidth and energy fees paid into the transaction fee pool, from which block producers are rewarded; set only when the transaction fee pool (`getAllowTransactionFeePool`) is enabled. + + `withdraw_expire_amount`: expired unstaked TRX withdrawn to the balance by this transaction. + + `cancel_unfreezeV2_amount`: for `CancelAllUnfreezeV2Contract`, the unstaked amounts staked again, keyed by resource type. + ```java message TransactionInfo { enum code { @@ -788,6 +878,11 @@ Transaction and transaction-related messages. int64 exchange_withdraw_another_amount = 20; int64 exchange_id = 21; int64 shielded_transaction_fee = 22; + bytes orderId = 25; + repeated MarketOrderDetail orderDetails = 26; + int64 packingFee = 27; + int64 withdraw_expire_amount = 28; + map cancel_unfreezeV2_amount = 29; } ``` - message `Transactions` @@ -829,7 +924,7 @@ Transaction and transaction-related messages. Contract and contract-related messages. -- Tron has 33 types of Contracts declared within [`Transaction`](#trans). +- Tron has 41 types of Contracts declared within [`Transaction`](#trans). - message `Contract` @@ -898,7 +993,7 @@ Contract and contract-related messages. } ``` -- There are 15 types of results while deploying contracts (refer to `Transaction.Result`): +- There are 16 types of results while deploying contracts (refer to `Transaction.Result`): ```java enum contractResult { @@ -917,6 +1012,7 @@ Contract and contract-related messages. JVM_STACK_OVER_FLOW = 12; UNKNOWN = 13; TRANSFER_FAILED = 14; + INVALID_CODE = 15; } ``` @@ -1531,6 +1627,114 @@ Contract and contract-related messages. ``` attributes' type refer to [Shield Contract Related](#shieldc) + + - message `FreezeBalanceV2Contract` + + Stakes TRX under Stake 2.0 to obtain bandwidth, energy, or, under the new resource model (`getAllowNewResourceModel`), TRON Power. + + `owner_address`: address of owner. + + `frozen_balance`: amount of TRX to stake, in sun; at least 1 TRX and no more than the account balance. + + `resource`: type of resource to obtain: BANDWIDTH / ENERGY / TRON_POWER. + + ```java + message FreezeBalanceV2Contract { + bytes owner_address = 1; + int64 frozen_balance = 2; + ResourceCode resource = 3; + } + ``` + + - message `UnfreezeBalanceV2Contract` + + Unstakes TRX staked under Stake 2.0. The amount becomes withdrawable after the unstaking period (`getUnfreezeDelayDays` days), and an account can have at most 32 unstakes pending at a time. Unstaked amounts whose period has already ended are withdrawn to the balance in the same transaction. + + `owner_address`: address of owner. + + `unfreeze_balance`: amount of TRX to unstake, in sun. + + `resource`: type of resource the TRX was staked for: BANDWIDTH / ENERGY / TRON_POWER. + + ```java + message UnfreezeBalanceV2Contract { + bytes owner_address = 1; + int64 unfreeze_balance = 2; + ResourceCode resource = 3; + } + ``` + + - message `WithdrawExpireUnfreezeContract` + + Withdraws all unstaked TRX whose unstaking period has ended to the account balance. + + `owner_address`: address of owner. + + ```java + message WithdrawExpireUnfreezeContract { + bytes owner_address = 1; + } + ``` + + - message `DelegateResourceContract` + + Delegates the bandwidth or energy of TRX staked under Stake 2.0 to another account. + + `owner_address`: address of owner. + + `resource`: type of resource to delegate: BANDWIDTH / ENERGY. + + `balance`: amount of staked TRX whose resource is delegated, in sun; at least 1 TRX. + + `receiver_address`: account that receives the resource; it cannot be the owner or a contract. + + `lock`: if true, the delegation cannot be reclaimed until the lock period ends. + + `lock_period`: lock period in blocks (3 seconds each), up to `getMaxDelegateLockPeriod`; `0` means the default of 3 days. A new locked delegation of the same resource to the same receiver moves the lock end of all balance already locked for that resource and receiver to the new end time, and its lock period cannot be shorter than the time left on the current lock. + + ```java + 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` + + Reclaims resource delegated with `DelegateResourceContract`. Locked delegations can be reclaimed only after their lock period ends. + + `owner_address`: address of owner. + + `resource`: type of resource to reclaim: BANDWIDTH / ENERGY. + + `balance`: amount of delegated staked TRX to reclaim, in sun. + + `receiver_address`: account the resource was delegated to. + + ```java + message UnDelegateResourceContract { + bytes owner_address = 1; + ResourceCode resource = 2; + int64 balance = 3; + bytes receiver_address = 4; + } + ``` + + - message `CancelAllUnfreezeV2Contract` + + Cancels all pending Stake 2.0 unstakes: amounts still in the unstaking period are staked again, and amounts whose period has ended are withdrawn to the balance. + + `owner_address`: address of owner. + + ```java + message CancelAllUnfreezeV2Contract { + bytes owner_address = 1; + } + ``` @@ -1554,6 +1758,7 @@ message `SmartContract` has multiple attributes and nested message `ABI` Event = 3; Fallback = 4; Receive = 5; + Error = 6; } ``` @@ -1623,6 +1828,8 @@ message `SmartContract` has multiple attributes and nested message `ABI` `code_hash`: hash of smart contract bytecode. `trx_hash`: transactionId of Deploying contract transaction. + + `version`: contract version; `1` for contracts created while EVM compatibility (`getAllowTvmCompatibleEvm`) is enabled, otherwise `0`. ```java message SmartContract { @@ -1635,6 +1842,7 @@ message `SmartContract` has multiple attributes and nested message `ABI` Event = 3; Fallback = 4; Receive = 5; + Error = 6; } message Param { bool indexed = 1; @@ -1670,6 +1878,7 @@ message `SmartContract` has multiple attributes and nested message `ABI` int64 origin_energy_limit = 8; bytes code_hash = 9; bytes trx_hash = 10; + int32 version = 11; } ``` @@ -2053,6 +2262,10 @@ message `SmartContract` has multiple attributes and nested message `ABI` 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; } ``` @@ -2100,6 +2313,12 @@ message `SmartContract` has multiple attributes and nested message `ABI` `signature`: signature for sender. + `nodeType`: node type, `0` for a full node and `1` for a lite fullnode. + + `lowestBlockNum`: lowest block number stored by a lite fullnode; `0` for a full node. + + `codeVersion`: java-tron version of the sender. + ```java message DisconnectMessage { ReasonCode reason = 1; @@ -2119,6 +2338,9 @@ message `SmartContract` has multiple attributes and nested message `ABI` BlockId headBlockId = 6; bytes address = 7; bytes signature = 8; + int32 nodeType = 9; + int64 lowestBlockNum = 10; + bytes codeVersion = 11; } ``` diff --git a/framework/build.gradle b/framework/build.gradle index 8edd6714f95..26699123515 100644 --- a/framework/build.gradle +++ b/framework/build.gradle @@ -1,6 +1,5 @@ plugins { id "org.gradle.test-retry" version "1.5.9" - id "org.sonarqube" version "2.6" id "com.gorylenko.gradle-git-properties" version "2.4.1" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index a73c4715fe1..9eb70e3f061 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -2707,37 +2707,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/build.gradle b/plugins/build.gradle index ee43646dadd..c6881f3131c 100644 --- a/plugins/build.gradle +++ b/plugins/build.gradle @@ -1,7 +1,3 @@ -plugins { - id "org.sonarqube" version "2.6" -} - apply plugin: 'application' apply plugin: 'checkstyle' 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 f393447e42e..330c1af0b2f 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 @@ -1,3 +1,5 @@ +> ⚠️ **本副本已过时(最后更新于 2022 年)。** 当前的协议说明见 [`docs/protobuf-protocol-document.md`](../../../../docs/protobuf-protocol-document.md),字段定义以本目录下的 `.proto` 文件为准;此副本仅作历史参考保留。 + # TRON protobuf protocol ## TRON使用Google protobuf协议,协议内容涉及到账户,区块,传输多个层面。 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 7d23f5c1f49..757512ef519 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 @@ -1,4 +1,6 @@ +> ⚠️ **This copy is outdated (last updated 2022).** See [`docs/protobuf-protocol-document.md`](../../../../docs/protobuf-protocol-document.md) for the current guide; the `.proto` files in this directory are the source of truth. This copy is kept only for historical reference. + # Protobuf protocol ## The protocol of TRON is defined by Google Protobuf and contains a range of layers, from account, block to transfer. diff --git a/sonar-project.properties b/sonar-project.properties deleted file mode 100644 index 220dbc068cc..00000000000 --- a/sonar-project.properties +++ /dev/null @@ -1,19 +0,0 @@ -sonar.projectKey=java-tron -sonar.projectName=java-tron -sonar.projectVersion=2.1 -# ===================================================== -# Meta-data for the project -# ===================================================== -sonar.links.homepage=https://github.com/tronprotocol/java-tron -sonar.links.ci=https://travis-ci.org/tronprotocol/java-tron -sonar.links.scm=https://github.com/tronprotocol/java-tron -sonar.links.issue=https://github.com/tronprotocol/java-tron/issues -# ===================================================== -# Properties that will be shared amongst all modules -# ===================================================== -# SQ standard properties -sonar.sources=./actuator/src,./framework/src/main,./consensus/src,./chainbase/src -sonar.java.binaries=./actuator/build/classes,./framework/build/classes,./consensus/build/classes,\ - ./chainbase/build/classes -# ===================================================== -# Properties that will be shared amongst all modules \ No newline at end of file