|
| 1 | +package org.tron.core.db; |
| 2 | + |
| 3 | +import com.google.protobuf.ByteString; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | +import org.bouncycastle.util.encoders.Hex; |
| 6 | +import org.tron.common.runtime.vm.DataWord; |
| 7 | +import org.tron.core.capsule.AccountCapsule; |
| 8 | +import org.tron.core.capsule.BlockCapsule; |
| 9 | +import org.tron.core.capsule.CodeCapsule; |
| 10 | +import org.tron.core.capsule.ContractCapsule; |
| 11 | +import org.tron.core.vm.program.Storage; |
| 12 | +import org.tron.protos.Protocol; |
| 13 | +import org.tron.protos.Protocol.Account; |
| 14 | +import org.tron.protos.contract.SmartContractOuterClass.SmartContract; |
| 15 | + |
| 16 | +/** |
| 17 | + * TIP-2935 (EIP-2935): serve historical block hashes from state. |
| 18 | + * |
| 19 | + * <p>Approach A1 — at proposal activation, deploy the BlockHashHistory bytecode |
| 20 | + * and minimal contract/account metadata via direct store writes; on every block |
| 21 | + * (before the tx loop) write the parent block hash to slot |
| 22 | + * {@code (blockNum - 1) % HISTORY_SERVE_WINDOW} via {@link Storage}. |
| 23 | + * No VM execution is needed for {@code set()}; user contracts read via normal |
| 24 | + * STATICCALL which executes the deployed bytecode. |
| 25 | + */ |
| 26 | +@Slf4j(topic = "DB") |
| 27 | +public class HistoryBlockHashUtil { |
| 28 | + |
| 29 | + public static final long HISTORY_SERVE_WINDOW = 8191L; |
| 30 | + |
| 31 | + // 21-byte TRON address (0x41 prefix + 20-byte EVM address 0x0000F908...2935) |
| 32 | + public static final byte[] HISTORY_STORAGE_ADDRESS = |
| 33 | + Hex.decode("410000f90827f1c53a10cb7a02335b175320002935"); |
| 34 | + |
| 35 | + // Recovered sender of the EIP-2935 presigned (no-private-key) deploy |
| 36 | + // transaction on Ethereum, in TRON 21-byte form. Used as {@code originAddress} |
| 37 | + // on the deployed SmartContract so the deployer-of-record matches Ethereum |
| 38 | + // byte-for-byte; cross-chain tooling that inspects this field sees the same |
| 39 | + // address on both sides. |
| 40 | + public static final byte[] HISTORY_DEPLOYER_ADDRESS = |
| 41 | + Hex.decode("413462413af4609098e1e27a490f554f260213d685"); |
| 42 | + |
| 43 | + // TIP-2935 runtime bytecode (83 bytes, no constructor prefix). Identical to |
| 44 | + // EIP-2935's so the same address resolves to the same code on both chains. |
| 45 | + public static final byte[] HISTORY_STORAGE_CODE = Hex.decode( |
| 46 | + "3373fffffffffffffffffffffffffffffffffffffffe" |
| 47 | + + "14604657602036036042575f35600143038111604257" |
| 48 | + + "611fff81430311604257611fff9006545f5260205ff3" |
| 49 | + + "5b5f5ffd5b5f35611fff60014303065500"); |
| 50 | + |
| 51 | + public static final String HISTORY_STORAGE_NAME = "BlockHashHistory"; |
| 52 | + |
| 53 | + // Account template for the new-account branch of {@code deploy()} (no prior |
| 54 | + // state at the canonical address). Equivalent to create2's |
| 55 | + // {@code createAccount(addr, name, Contract)}: only type, accountName, and |
| 56 | + // address are set. The pre-existing-account branch never uses this template |
| 57 | + // — it mutates the existing capsule in place to preserve balance / asset |
| 58 | + // state, mirroring the CREATE2 collision path. Safe to share: the proto is |
| 59 | + // immutable, and AccountCapsule mutations rebuild via {@code toBuilder}. |
| 60 | + private static final Account HISTORY_STORAGE_ACCOUNT = Account.newBuilder() |
| 61 | + .setType(Protocol.AccountType.Contract) |
| 62 | + .setAccountName(ByteString.copyFromUtf8(HISTORY_STORAGE_NAME)) |
| 63 | + .setAddress(ByteString.copyFrom(HISTORY_STORAGE_ADDRESS)) |
| 64 | + .build(); |
| 65 | + |
| 66 | + // SmartContract template: every field is fixed at activation time, so the |
| 67 | + // proto is immutable and shared across calls. Mirrors the create2 path's |
| 68 | + // shape (version=0, contractAddress, consumeUserResourcePercent=100, |
| 69 | + // originAddress) plus a descriptive name. No trxHash since activation is |
| 70 | + // not a transaction. |
| 71 | + private static final SmartContract HISTORY_STORAGE_CONTRACT = SmartContract.newBuilder() |
| 72 | + .setName(HISTORY_STORAGE_NAME) |
| 73 | + .setContractAddress(ByteString.copyFrom(HISTORY_STORAGE_ADDRESS)) |
| 74 | + .setOriginAddress(ByteString.copyFrom(HISTORY_DEPLOYER_ADDRESS)) |
| 75 | + .setConsumeUserResourcePercent(100L) |
| 76 | + .build(); |
| 77 | + |
| 78 | + private HistoryBlockHashUtil() { |
| 79 | + } |
| 80 | + |
| 81 | + /** |
| 82 | + * Deploy the TIP-2935 BlockHashHistory contract at {@code HISTORY_STORAGE_ADDRESS}. |
| 83 | + * If foreign code or contract metadata already sits at the canonical address, |
| 84 | + * logs a warning and returns without writing — the collision is deterministic |
| 85 | + * across nodes (same pre-state ⇒ same decision), so the proposal flag still |
| 86 | + * commits and chain consensus is intact. The foreign contract executes as-is |
| 87 | + * on every node; TIP-2935 functionality is silently absent at this address. |
| 88 | + * A SHA-3 pre-image of the address is the only realistic way that branch |
| 89 | + * fires, so it's belt-and-braces. A pre-existing non-contract account at the |
| 90 | + * address is the common case (anyone can transfer TRX there to activate it |
| 91 | + * as an EOA), so we upgrade its type to {@code Contract} in place — matching |
| 92 | + * the CREATE2 collision branch ({@code updateAccountType} + |
| 93 | + * {@code clearDelegatedResource}) and preserving balance/asset state. |
| 94 | + * |
| 95 | + * <p>Called only from {@code ProposalService} inside maintenance-time block |
| 96 | + * processing. Proposal validation rejects re-activation, so this runs at most |
| 97 | + * once per chain history; the three store writes share the block's revoking |
| 98 | + * session, so any node-local exception (RocksDB / IO) propagates and rolls |
| 99 | + * the {@code saveAllowTvmPrague(1)} write back atomically. |
| 100 | + */ |
| 101 | + public static void deploy(Manager manager) { |
| 102 | + if (manager.getCodeStore().has(HISTORY_STORAGE_ADDRESS) |
| 103 | + || manager.getContractStore().has(HISTORY_STORAGE_ADDRESS)) { |
| 104 | + logger.warn("TIP-2935: foreign state at {}, skipping deploy", |
| 105 | + Hex.toHexString(HISTORY_STORAGE_ADDRESS)); |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + manager.getCodeStore().put(HISTORY_STORAGE_ADDRESS, |
| 110 | + new CodeCapsule(HISTORY_STORAGE_CODE)); |
| 111 | + manager.getContractStore().put(HISTORY_STORAGE_ADDRESS, |
| 112 | + new ContractCapsule(HISTORY_STORAGE_CONTRACT)); |
| 113 | + |
| 114 | + AccountCapsule account = manager.getAccountStore().get(HISTORY_STORAGE_ADDRESS); |
| 115 | + boolean accountExisting = account != null; |
| 116 | + if (!accountExisting) { |
| 117 | + account = new AccountCapsule(HISTORY_STORAGE_ACCOUNT); |
| 118 | + } else { |
| 119 | + account.updateAccountType(Protocol.AccountType.Contract); |
| 120 | + account.clearDelegatedResource(); |
| 121 | + } |
| 122 | + manager.getAccountStore().put(HISTORY_STORAGE_ADDRESS, account); |
| 123 | + |
| 124 | + // Flip the install marker only after all three store writes succeed; this |
| 125 | + // gates the per-block write() path so a skipped deploy never mutates |
| 126 | + // foreign storage. Any node-local exception above propagates and rolls |
| 127 | + // the marker back together with the partial writes via the revoking session. |
| 128 | + manager.getDynamicPropertiesStore().saveBlockHashHistoryInstalled(1L); |
| 129 | + |
| 130 | + logger.info("TIP-2935: deployed BlockHashHistory at {} (preExistingAccount={})", |
| 131 | + Hex.toHexString(HISTORY_STORAGE_ADDRESS), accountExisting); |
| 132 | + } |
| 133 | + |
| 134 | + /** |
| 135 | + * Write the parent block hash to storage at slot |
| 136 | + * {@code (blockNum - 1) % HISTORY_SERVE_WINDOW}. Called from |
| 137 | + * {@code Manager.processBlock} before the tx loop so transactions can SLOAD |
| 138 | + * it via STATICCALL to the deployed bytecode. |
| 139 | + */ |
| 140 | + public static void write(Manager manager, BlockCapsule block) { |
| 141 | + // Genesis has no parent; applyBlock never invokes this for block 0, but be |
| 142 | + // explicit so (0-1) % 8191 = -1 in Java can never corrupt a slot. |
| 143 | + if (block.getNum() <= 0) { |
| 144 | + return; |
| 145 | + } |
| 146 | + // Defense-in-depth: deploy() skips on foreign state at the canonical |
| 147 | + // address, but the proposal flag still commits. Gate on the install |
| 148 | + // marker (set at the tail of a successful deploy()) so write() can never |
| 149 | + // overwrite an unrelated contract's storage. Single store hit, cached. |
| 150 | + if (!manager.getDynamicPropertiesStore().isBlockHashHistoryInstalled()) { |
| 151 | + return; |
| 152 | + } |
| 153 | + long slot = (block.getNum() - 1) % HISTORY_SERVE_WINDOW; |
| 154 | + Storage storage = new Storage(HISTORY_STORAGE_ADDRESS, manager.getStorageRowStore()); |
| 155 | + storage.put(new DataWord(slot), new DataWord(block.getParentHash().getBytes())); |
| 156 | + storage.commit(); |
| 157 | + } |
| 158 | +} |
0 commit comments