|
2 | 2 |
|
3 | 3 | import static org.mockito.Mockito.mock; |
4 | 4 |
|
| 5 | +import com.google.protobuf.ByteString; |
5 | 6 | import java.lang.reflect.Field; |
6 | 7 | import org.junit.Assert; |
7 | 8 | import org.junit.Test; |
8 | 9 | import org.mockito.Mockito; |
9 | 10 | import org.tron.common.TestConstants; |
10 | 11 | import org.tron.common.parameter.CommonParameter; |
| 12 | +import org.tron.common.utils.ByteArray; |
11 | 13 | import org.tron.common.utils.Sha256Hash; |
12 | 14 | import org.tron.core.ChainBaseManager; |
| 15 | +import org.tron.core.Wallet; |
13 | 16 | import org.tron.core.capsule.BlockCapsule; |
| 17 | +import org.tron.core.capsule.TransactionCapsule; |
14 | 18 | import org.tron.core.config.args.Args; |
| 19 | +import org.tron.core.exception.P2pException; |
| 20 | +import org.tron.core.exception.P2pException.TypeEnum; |
| 21 | +import org.tron.protos.Protocol.Transaction.Contract.ContractType; |
| 22 | +import org.tron.protos.contract.BalanceContract.TransferContract; |
15 | 23 |
|
16 | 24 | public class TronNetDelegateTest { |
17 | 25 |
|
@@ -49,4 +57,37 @@ public void test() throws Exception { |
49 | 57 |
|
50 | 58 | Assert.assertTrue(!tronNetDelegate.isBlockUnsolidified()); |
51 | 59 | } |
| 60 | + |
| 61 | + @Test |
| 62 | + public void testValidBlockMerkleRoot() throws Exception { |
| 63 | + Args.setParam(new String[] {}, TestConstants.TEST_CONF); |
| 64 | + |
| 65 | + String parentHash = "9938a342238077182498b464ac0292229938a342238077182498b464ac029222"; |
| 66 | + BlockCapsule block = new BlockCapsule(1, |
| 67 | + Sha256Hash.wrap(ByteString.copyFrom(ByteArray.fromHexString(parentHash))), |
| 68 | + System.currentTimeMillis(), |
| 69 | + ByteString.copyFrom("witness".getBytes())); |
| 70 | + block.setMerkleRoot(); |
| 71 | + |
| 72 | + // Add a transaction after setMerkleRoot, making the stored merkle root stale. |
| 73 | + TransferContract transferContract = TransferContract.newBuilder() |
| 74 | + .setAmount(1L) |
| 75 | + .setOwnerAddress(ByteString.copyFrom("0x0000000000000000000".getBytes())) |
| 76 | + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString( |
| 77 | + Wallet.getAddressPreFixString() + "A389132D6639FBDA4FBC8B659264E6B7C90DB086"))) |
| 78 | + .build(); |
| 79 | + block.addTransaction( |
| 80 | + new TransactionCapsule(transferContract, ContractType.TransferContract)); |
| 81 | + |
| 82 | + // Wrap in a fresh BlockCapsule so the merkleValidated flag is reset. |
| 83 | + BlockCapsule tampered = new BlockCapsule(block.getInstance()); |
| 84 | + |
| 85 | + TronNetDelegate tronNetDelegate = new TronNetDelegate(); |
| 86 | + try { |
| 87 | + tronNetDelegate.validBlock(tampered); |
| 88 | + Assert.fail("Expected P2pException for tampered merkle root"); |
| 89 | + } catch (P2pException e) { |
| 90 | + Assert.assertEquals(TypeEnum.BLOCK_MERKLE_ERROR, e.getType()); |
| 91 | + } |
| 92 | + } |
52 | 93 | } |
0 commit comments