-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(vm): implement TIP-2935 serve historical block hashes from state #6686
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yanghang8612
wants to merge
8
commits into
tronprotocol:develop
Choose a base branch
from
yanghang8612:feat/tip-2935-historical-blockhash
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1e1167a
feat(vm): serve historical block hashes from state (TIP-2935)
yanghang8612 8735986
fix(vm): deploy TIP-2935 history contract on config-driven activation
yanghang8612 967dd86
refactor(vm): use Manager store accessors directly in HistoryBlockHas…
yanghang8612 c4dde34
fix(vm): validate existing state before TIP-2935 deploy and self-heal…
yanghang8612 f97bcdc
refactor(vm): rename HistoryStorage to BlockHashHistory and fix line …
yanghang8612 344f418
fix(vm): address TIP-2935 review feedback
yanghang8612 f60c100
refactor(vm): simplify TIP-2935 deploy now that it runs at most once
yanghang8612 34aa2fb
refactor(vm): TIP-2935 deploy skips on foreign state instead of throwing
yanghang8612 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
133 changes: 133 additions & 0 deletions
133
framework/src/main/java/org/tron/core/db/HistoryBlockHashUtil.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| package org.tron.core.db; | ||
|
|
||
| import static java.lang.System.arraycopy; | ||
|
|
||
| import com.google.protobuf.ByteString; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.bouncycastle.util.encoders.Hex; | ||
| import org.tron.common.crypto.Hash; | ||
| import org.tron.common.runtime.vm.DataWord; | ||
| import org.tron.core.capsule.AccountCapsule; | ||
| import org.tron.core.capsule.BlockCapsule; | ||
| import org.tron.core.capsule.CodeCapsule; | ||
| import org.tron.core.capsule.ContractCapsule; | ||
| import org.tron.core.capsule.StorageRowCapsule; | ||
| import org.tron.protos.Protocol; | ||
| import org.tron.protos.contract.SmartContractOuterClass.SmartContract; | ||
|
|
||
| /** | ||
| * TIP-2935 (EIP-2935): serve historical block hashes from state. | ||
| * | ||
| * <p>Approach A1 — at proposal activation, deploy the BlockHashHistory bytecode | ||
| * and minimal contract/account metadata via direct store writes; on every block | ||
| * (before the tx loop) write the parent block hash to slot | ||
| * {@code (blockNum - 1) % HISTORY_SERVE_WINDOW} via direct StorageRowStore write. | ||
| * No VM execution is needed for {@code set()}; user contracts read via normal | ||
| * STATICCALL which executes the deployed bytecode. | ||
| * | ||
| * <p>Storage key layout replicates {@code Storage.compose()} for | ||
| * {@code contractVersion=0}: first 16 bytes of {@code sha3(address)} followed by | ||
| * the last 16 bytes of the 32-byte slot key. | ||
| */ | ||
| @Slf4j(topic = "DB") | ||
| public class HistoryBlockHashUtil { | ||
|
|
||
| public static final long HISTORY_SERVE_WINDOW = 8191L; | ||
|
|
||
| // 21-byte TRON address (0x41 prefix + 20-byte EVM address 0x0000F908...2935) | ||
| public static final byte[] HISTORY_STORAGE_ADDRESS = | ||
| Hex.decode("410000f90827f1c53a10cb7a02335b175320002935"); | ||
|
|
||
| // TIP-2935 runtime bytecode (83 bytes, no constructor prefix). Identical to | ||
| // EIP-2935's so the same address resolves to the same code on both chains. | ||
| public static final byte[] HISTORY_STORAGE_CODE = Hex.decode( | ||
| "3373fffffffffffffffffffffffffffffffffffffffe" | ||
| + "14604657602036036042575f35600143038111604257" | ||
| + "611fff81430311604257611fff9006545f5260205ff3" | ||
| + "5b5f5ffd5b5f35611fff60014303065500"); | ||
|
|
||
| public static final String BLOCK_HASH_HISTORY_NAME = "BlockHashHistory"; | ||
|
|
||
| private static final int PREFIX_BYTES = 16; | ||
|
|
||
| private HistoryBlockHashUtil() { | ||
| } | ||
|
|
||
| /** | ||
| * Compose the raw StorageRowStore key for {@code (address, slot)} at | ||
| * {@code contractVersion=0}. Must match {@code Storage.compose()} byte-for-byte | ||
| * so that a subsequent VM SLOAD(slot) at this address reads back the written value. | ||
| */ | ||
| public static byte[] composeStorageKey(long slot, byte[] address) { | ||
| byte[] addrHash = Hash.sha3(address); | ||
| byte[] slotKey = new DataWord(slot).getData(); | ||
| byte[] result = new byte[32]; | ||
| arraycopy(addrHash, 0, result, 0, PREFIX_BYTES); | ||
| arraycopy(slotKey, PREFIX_BYTES, result, PREFIX_BYTES, PREFIX_BYTES); | ||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * Deploy the TIP-2935 BlockHashHistory contract at {@code HISTORY_STORAGE_ADDRESS}. | ||
| * If foreign code or contract metadata already sits at the canonical address, | ||
| * logs a warning and returns without writing — the collision is deterministic | ||
| * across nodes (same pre-state ⇒ same decision), so the flag still commits | ||
| * and consensus is intact; user STATICCALLs to the address return empty at | ||
| * the user level, not the chain level. A SHA-3 pre-image of the address is | ||
| * the only realistic way that branch fires, so it's belt-and-braces. A | ||
| * pre-existing non-contract account at the address is the common case (anyone | ||
| * can transfer TRX there to activate it as an EOA), so we upgrade its type to | ||
| * {@code Contract} in place, preserving balance/asset state. | ||
| * | ||
| * <p>Called only from {@code ProposalService} inside maintenance-time block | ||
| * processing. Proposal validation rejects re-activation, so this runs at most | ||
| * once per chain history; the three store writes share the block's revoking | ||
| * session, so any node-local exception (RocksDB / IO) propagates and rolls | ||
| * the {@code saveAllowTvmPrague(1)} write back atomically. | ||
| */ | ||
| public static void deploy(Manager manager) { | ||
| byte[] addr = HISTORY_STORAGE_ADDRESS; | ||
| if (manager.getCodeStore().has(addr) || manager.getContractStore().has(addr)) { | ||
| logger.warn("TIP-2935: foreign state at {}, skipping deploy", | ||
| Hex.toHexString(addr)); | ||
| return; | ||
| } | ||
|
|
||
| manager.getCodeStore().put(addr, new CodeCapsule(HISTORY_STORAGE_CODE)); | ||
| manager.getContractStore().put(addr, new ContractCapsule(SmartContract.newBuilder() | ||
| .setName(BLOCK_HASH_HISTORY_NAME) | ||
| .setContractAddress(ByteString.copyFrom(addr)) | ||
| .setOriginAddress(ByteString.copyFrom(addr)) | ||
| .setConsumeUserResourcePercent(100L) | ||
| .setOriginEnergyLimit(0L) | ||
| .build())); | ||
|
|
||
| boolean preExistingAccount = manager.getAccountStore().has(addr); | ||
| AccountCapsule account = preExistingAccount | ||
| ? manager.getAccountStore().get(addr) | ||
| : new AccountCapsule(ByteString.copyFrom(addr), Protocol.AccountType.Contract); | ||
| account.updateAccountType(Protocol.AccountType.Contract); | ||
| manager.getAccountStore().put(addr, account); | ||
|
|
||
| logger.info("TIP-2935: deployed BlockHashHistory at {} (preExistingAccount={})", | ||
| Hex.toHexString(addr), preExistingAccount); | ||
| } | ||
|
|
||
| /** | ||
| * Write the parent block hash to storage at slot | ||
| * {@code (blockNum - 1) % HISTORY_SERVE_WINDOW}. Called from | ||
| * {@code Manager.processBlock} before the tx loop so transactions can SLOAD | ||
| * it via STATICCALL to the deployed bytecode. | ||
| */ | ||
| public static void write(Manager manager, BlockCapsule block) { | ||
| // Genesis has no parent; applyBlock never invokes this for block 0, but be | ||
| // explicit so (0-1) % 8191 = -1 in Java can never corrupt a slot. | ||
| if (block.getNum() <= 0) { | ||
| return; | ||
| } | ||
| long slot = (block.getNum() - 1) % HISTORY_SERVE_WINDOW; | ||
| byte[] storageKey = composeStorageKey(slot, HISTORY_STORAGE_ADDRESS); | ||
| byte[] parentHash = block.getParentHash().getBytes(); | ||
| manager.getStorageRowStore().put(storageKey, new StorageRowCapsule(storageKey, parentHash)); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The idempotent
deploy()with per-storehas()checks and the genesis guard inwrite()are really clean.Minor: would it be helpful to add a log line in
deploy()/deployIfMissing()for easier troubleshooting during upgrades?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the nudge — good point, one
infolog is cheap and pays off the first time someone has to trace when TIP-2935 actually landed on a given node.Just pushed it in c4dde34: a single
logger.infoinside theCodeStorewrite branch ofdeploy(), guarded by!has(addr)so it only fires the instant fresh bytecode first lands. Steady-state restarts stay silent.Format:
Topic is
DB, matching the convention inorg.tron.core.db.backup.*etc.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for pushing this in — the
!has(addr)guard plus@Slf4j(topic = "DB")is spot-on, and having steady-state restarts stay silent is exactly the right trade-off. 🎯Nice bonus I noticed while reading the commit: you also took the chance to rename the constant to
BlockHashHistory(clearer domain naming; the log string carries the new name too) and addvalidateExistingOrThrow()sodeploy()now validates-first-then-writes. That pattern cleanly handles both the "canonical address already occupied by foreign state" case and the "crashed between the three store writes" partial-install case — a solid defensive improvement that goes well beyond the original log-line ask. 👍There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks — and good eye on the rename.
BlockHashHistoryreads better everywhere it surfaces (proposal name, log topic, store comments), andvalidateExistingOrThrow()is the right shape for the three-store triplet: a mid-deploy()crash now surfaces as a loud mismatch on restart rather than a silently partial install acrossCodeStore/ContractStore/AccountStore. Appreciated the careful read across the whole commit, not just the spot I asked about.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Anytime! The simplified
deployIfMissing(gate on the flag, delegate todeploy()so the validate-first path runs regardless of which store crashed mid-write) is a particularly tidy way to fold partial-install recovery into the normal deploy path — no separate code path to maintain. 👍 Looking forward to seeing TIP-2935 land.