Remove QuantityWrapper. Use the Difficulty class extending both UInt256 and Quantity instead. (#274)

Signed-off-by: Antoine Toulme <antoine@lunar-ocean.com>
pull/275/head
Antoine Toulme 5 years ago committed by Adrian Sutton
parent 58f22eb9ed
commit bf7493de29
  1. 4
      acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/BlockUtils.java
  2. 6
      besu/src/main/java/org/hyperledger/besu/chainimport/RlpBlockImporter.java
  3. 7
      besu/src/main/java/org/hyperledger/besu/services/BesuEventsImpl.java
  4. 10
      besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java
  5. 2
      consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueBlockHashing.java
  6. 2
      consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRule.java
  7. 6
      consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueBlockHashingTest.java
  8. 10
      consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java
  9. 4
      consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java
  10. 2
      consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactory.java
  11. 3
      consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHashingTest.java
  12. 6
      consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java
  13. 2
      consensus/ibftlegacy/src/main/java/org/hyperledger/besu/consensus/ibftlegacy/IbftBlockHashing.java
  14. 2
      consensus/ibftlegacy/src/main/java/org/hyperledger/besu/consensus/ibftlegacy/IbftBlockHeaderValidationRulesetFactory.java
  15. 4
      consensus/ibftlegacy/src/test/java/org/hyperledger/besu/consensus/ibftlegacy/IbftBlockHashingTest.java
  16. 4
      consensus/ibftlegacy/src/test/java/org/hyperledger/besu/consensus/ibftlegacy/IbftBlockHeaderValidationRulesetFactoryTest.java
  17. 5
      ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcResponseUtils.java
  18. 6
      ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetFilterChangesIntegrationTest.java
  19. 5
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java
  20. 4
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/NormalBlockAdapter.java
  21. 8
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/BlockResult.java
  22. 5
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/UncleBlockResult.java
  23. 9
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockWithMetadata.java
  24. 13
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTest.java
  25. 4
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminNodeInfoTest.java
  26. 3
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStorageRangeAtTest.java
  27. 2
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockTest.java
  28. 6
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockHashAndIndexTest.java
  29. 6
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockNumberAndIndexTest.java
  30. 10
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/subscription/blockheaders/NewBlockHeadersSubscriptionServiceTest.java
  31. 4
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueriesLogCacheTest.java
  32. 2
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueriesTest.java
  33. 4
      ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java
  34. 2
      ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/EthHashBlockCreator.java
  35. 4
      ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockTransactionSelectorTest.java
  36. 6
      ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/EthHashBlockCreatorTest.java
  37. 6
      ethereum/core/src/jmh/java/org/hyperledger/besu/ethereum/vm/operations/OperationBenchmarkHelper.java
  38. 5
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/Blockchain.java
  39. 7
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/BlockchainStorage.java
  40. 9
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/ChainHead.java
  41. 20
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchain.java
  42. 5
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/GenesisState.java
  43. 7
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/BlockHeader.java
  44. 11
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/BlockHeaderBuilder.java
  45. 94
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/Difficulty.java
  46. 14
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/ProcessableBlockHeader.java
  47. 48
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/QuantityWrapper.java
  48. 3
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/SealableBlockHeader.java
  49. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/EthHash.java
  50. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/headervalidationrules/CalculatedDifficultyValidationRule.java
  51. 6
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/headervalidationrules/ProofOfWorkValidationRule.java
  52. 7
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/storage/keyvalue/KeyValueStoragePrefixedKeyBlockchainStorage.java
  53. 5
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/vm/operations/DifficultyOperation.java
  54. 8
      ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockDataGenerator.java
  55. 5
      ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockHeaderTestFixture.java
  56. 29
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchainTest.java
  57. 3
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/core/BlockHeaderMock.java
  58. 3
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java
  59. 11
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/headervalidationrules/ConstantFieldValidationRuleTest.java
  60. 7
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/headervalidationrules/ProofOfWorkValidationRuleTest.java
  61. 4
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/util/BlockchainUtilParameterizedTest.java
  62. 4
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/BlockchainReferenceTestCaseSpec.java
  63. 4
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/TestBlockchain.java
  64. 5
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/ChainHeadEstimate.java
  65. 16
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/ChainState.java
  66. 8
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/ChainStateSnapshot.java
  67. 4
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/EthPeer.java
  68. 4
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManager.java
  69. 13
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/messages/NewBlockMessage.java
  70. 12
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/messages/StatusMessage.java
  71. 6
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/BlockBroadcaster.java
  72. 8
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/BlockPropagationManager.java
  73. 5
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/BetterSyncTargetEvaluator.java
  74. 32
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ChainStateTest.java
  75. 10
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthPeersTest.java
  76. 4
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java
  77. 13
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTestUtil.java
  78. 8
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/RespondingEthPeer.java
  79. 6
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/NewBlockMessageTest.java
  80. 6
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/StatusMessageTest.java
  81. 10
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/BlockBroadcasterTest.java
  82. 14
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/BlockPropagationManagerTest.java
  83. 4
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java
  84. 4
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/TrailingPeerLimiterTest.java
  85. 12
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActionsTest.java
  86. 14
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockRetrieverTest.java
  87. 3
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/BetterSyncTargetEvaluatorTest.java
  88. 4
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncChainDownloaderForkTest.java
  89. 9
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncChainDownloaderTest.java
  90. 6
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java
  91. 18
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/state/SyncStateTest.java
  92. 4
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java
  93. 35
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolTest.java
  94. 2
      ethereum/retesteth/src/test/java/org/hyperledger/besu/ethereum/retesteth/methods/TestSetChainParamsTest.java

@ -19,11 +19,11 @@ import static org.hyperledger.besu.ethereum.core.Hash.fromHexString;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.web3j.protocol.core.methods.response.EthBlock.Block; import org.web3j.protocol.core.methods.response.EthBlock.Block;
public class BlockUtils { public class BlockUtils {
@ -42,7 +42,7 @@ public class BlockUtils {
fromHexString(block.getTransactionsRoot()), fromHexString(block.getTransactionsRoot()),
fromHexString(block.getReceiptsRoot()), fromHexString(block.getReceiptsRoot()),
LogsBloomFilter.fromHexString(block.getLogsBloom()), LogsBloomFilter.fromHexString(block.getLogsBloom()),
UInt256.fromHexString(block.getDifficultyRaw()), Difficulty.fromHexString(block.getDifficultyRaw()),
block.getNumber().longValue(), block.getNumber().longValue(),
block.getGasLimit().longValue(), block.getGasLimit().longValue(),
block.getGasUsed().longValue(), block.getGasUsed().longValue(),

@ -23,6 +23,7 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockImporter; import org.hyperledger.besu.ethereum.core.BlockImporter;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator; import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator;
import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode; import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode;
@ -42,7 +43,6 @@ import java.util.concurrent.Semaphore;
import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.tuweni.units.bigints.UInt256;
/** Tool for importing rlp-encoded block data from files. */ /** Tool for importing rlp-encoded block data from files. */
public class RlpBlockImporter { public class RlpBlockImporter {
@ -204,11 +204,11 @@ public class RlpBlockImporter {
public static final class ImportResult { public static final class ImportResult {
public final UInt256 td; public final Difficulty td;
final int count; final int count;
ImportResult(final UInt256 td, final int count) { ImportResult(final Difficulty td, final int count) {
this.td = td; this.td = td;
this.count = count; this.count = count;
} }

@ -18,9 +18,9 @@ import static java.util.stream.Collectors.toUnmodifiableList;
import org.hyperledger.besu.ethereum.api.query.LogsQuery; import org.hyperledger.besu.ethereum.api.query.LogsQuery;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.LogTopic; import org.hyperledger.besu.ethereum.core.LogTopic;
import org.hyperledger.besu.ethereum.core.LogWithMetadata; import org.hyperledger.besu.ethereum.core.LogWithMetadata;
import org.hyperledger.besu.ethereum.core.QuantityWrapper;
import org.hyperledger.besu.ethereum.eth.sync.BlockBroadcaster; import org.hyperledger.besu.ethereum.eth.sync.BlockBroadcaster;
import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; import org.hyperledger.besu.ethereum.eth.sync.state.SyncState;
import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
@ -36,7 +36,6 @@ import java.util.List;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
public class BesuEventsImpl implements BesuEvents { public class BesuEventsImpl implements BesuEvents {
private Blockchain blockchain; private Blockchain blockchain;
@ -134,7 +133,7 @@ public class BesuEventsImpl implements BesuEvents {
private static PropagatedBlockContext blockPropagatedContext( private static PropagatedBlockContext blockPropagatedContext(
final Supplier<BlockHeader> blockHeaderSupplier, final Supplier<BlockHeader> blockHeaderSupplier,
final Supplier<UInt256> totalDifficultySupplier) { final Supplier<Difficulty> totalDifficultySupplier) {
return new PropagatedBlockContext() { return new PropagatedBlockContext() {
@Override @Override
public BlockHeader getBlockHeader() { public BlockHeader getBlockHeader() {
@ -143,7 +142,7 @@ public class BesuEventsImpl implements BesuEvents {
@Override @Override
public Quantity getTotalDifficulty() { public Quantity getTotalDifficulty() {
return new QuantityWrapper(totalDifficultySupplier.get()); return totalDifficultySupplier.get();
} }
}; };
} }

@ -28,6 +28,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.TransactionTestFixture; import org.hyperledger.besu.ethereum.core.TransactionTestFixture;
import org.hyperledger.besu.ethereum.core.Wei; import org.hyperledger.besu.ethereum.core.Wei;
import org.hyperledger.besu.ethereum.core.WorldState; import org.hyperledger.besu.ethereum.core.WorldState;
@ -64,7 +65,6 @@ import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -183,7 +183,7 @@ public class BesuEventsImplTest {
serviceImpl.addBlockPropagatedListener(result::set); serviceImpl.addBlockPropagatedListener(result::set);
final Block block = generateBlock(); final Block block = generateBlock();
assertThat(result.get()).isNull(); assertThat(result.get()).isNull();
blockBroadcaster.propagate(block, UInt256.valueOf(1)); blockBroadcaster.propagate(block, Difficulty.of(1));
assertThat(result.get()).isNotNull(); assertThat(result.get()).isNotNull();
assertThat(result.get().getBlockHeader()).isEqualTo(block.getHeader()); assertThat(result.get().getBlockHeader()).isEqualTo(block.getHeader());
@ -197,7 +197,7 @@ public class BesuEventsImplTest {
assertThat(result.get()).isNull(); assertThat(result.get()).isNull();
final Block block = generateBlock(); final Block block = generateBlock();
blockBroadcaster.propagate(block, UInt256.valueOf(2)); blockBroadcaster.propagate(block, Difficulty.of(2));
assertThat(result.get()).isNotNull(); assertThat(result.get()).isNotNull();
assertThat(result.get().getBlockHeader()).isEqualTo(block.getHeader()); assertThat(result.get().getBlockHeader()).isEqualTo(block.getHeader());
@ -205,13 +205,13 @@ public class BesuEventsImplTest {
serviceImpl.removeBlockPropagatedListener(id); serviceImpl.removeBlockPropagatedListener(id);
result.set(null); result.set(null);
blockBroadcaster.propagate(generateBlock(), UInt256.valueOf(1)); blockBroadcaster.propagate(generateBlock(), Difficulty.of(1));
assertThat(result.get()).isNull(); assertThat(result.get()).isNull();
} }
@Test @Test
public void propagationWithoutSubscriptionsCompletes() { public void propagationWithoutSubscriptionsCompletes() {
blockBroadcaster.propagate(generateBlock(), UInt256.valueOf(1)); blockBroadcaster.propagate(generateBlock(), Difficulty.of(1));
} }
@Test @Test

@ -84,7 +84,7 @@ public class CliqueBlockHashing {
out.writeBytes(header.getTransactionsRoot()); out.writeBytes(header.getTransactionsRoot());
out.writeBytes(header.getReceiptsRoot()); out.writeBytes(header.getReceiptsRoot());
out.writeBytes(header.getLogsBloom().getBytes()); out.writeBytes(header.getLogsBloom().getBytes());
out.writeBytes(header.internalGetDifficulty().toMinimalBytes()); out.writeBytes(header.getDifficulty().toMinimalBytes());
out.writeLongScalar(header.getNumber()); out.writeLongScalar(header.getNumber());
out.writeLongScalar(header.getGasLimit()); out.writeLongScalar(header.getGasLimit());
out.writeLongScalar(header.getGasUsed()); out.writeLongScalar(header.getGasUsed());

@ -38,7 +38,7 @@ public class CliqueDifficultyValidationRule
new CliqueDifficultyCalculator(actualBlockCreator); new CliqueDifficultyCalculator(actualBlockCreator);
final BigInteger expectedDifficulty = diffCalculator.nextDifficulty(0, parent, protocolContext); final BigInteger expectedDifficulty = diffCalculator.nextDifficulty(0, parent, protocolContext);
final BigInteger actualDifficulty = header.internalGetDifficulty().toBigInteger(); final BigInteger actualDifficulty = header.getDifficulty().toBigInteger();
return expectedDifficulty.equals(actualDifficulty); return expectedDifficulty.equals(actualDifficulty);
} }

@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
@ -26,7 +27,6 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -82,7 +82,7 @@ public class CliqueBlockHashingTest {
// The following text was a dump from the geth console of the 30_000 block on Rinkeby. // The following text was a dump from the geth console of the 30_000 block on Rinkeby.
// eth.getBlock(30000) // eth.getBlock(30000)
final BlockHeaderBuilder builder = new BlockHeaderBuilder(); final BlockHeaderBuilder builder = new BlockHeaderBuilder();
builder.difficulty(UInt256.valueOf(2)); builder.difficulty(Difficulty.of(2));
builder.extraData( builder.extraData(
Bytes.fromHexString( Bytes.fromHexString(
"0xd783010600846765746887676f312e372e33856c696e7578000000000000000042eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f0c5bc40d0535af16266714ccb26fc49448c10bdf2969411514707d7442956b3397b09a980f4bea9347f70eea52183326247a0239b6d01fa0b07afc44e8a05463301")); "0xd783010600846765746887676f312e372e33856c696e7578000000000000000042eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f0c5bc40d0535af16266714ccb26fc49448c10bdf2969411514707d7442956b3397b09a980f4bea9347f70eea52183326247a0239b6d01fa0b07afc44e8a05463301"));
@ -117,7 +117,7 @@ public class CliqueBlockHashingTest {
private BlockHeader createGenesisBlock() { private BlockHeader createGenesisBlock() {
// The following was taken from the Rinkeby genesis file // The following was taken from the Rinkeby genesis file
final BlockHeaderBuilder builder = new BlockHeaderBuilder(); final BlockHeaderBuilder builder = new BlockHeaderBuilder();
builder.difficulty(UInt256.valueOf(1)); builder.difficulty(Difficulty.ONE);
builder.extraData( builder.extraData(
Bytes.fromHexString( Bytes.fromHexString(
"0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")); "0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"));

@ -31,12 +31,12 @@ import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.AddressHelpers;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.core.Util;
import java.util.List; import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -67,7 +67,7 @@ public class CliqueDifficultyValidationRuleTest {
@Test @Test
public void isTrueIfInTurnValidatorSuppliesDifficultyOfTwo() { public void isTrueIfInTurnValidatorSuppliesDifficultyOfTwo() {
final long IN_TURN_BLOCK_NUMBER = validatorList.size(); // i.e. proposer is 'in turn' final long IN_TURN_BLOCK_NUMBER = validatorList.size(); // i.e. proposer is 'in turn'
final UInt256 REPORTED_DIFFICULTY = UInt256.valueOf(2); final Difficulty REPORTED_DIFFICULTY = Difficulty.of(2);
blockHeaderBuilder.number(IN_TURN_BLOCK_NUMBER - 1L); blockHeaderBuilder.number(IN_TURN_BLOCK_NUMBER - 1L);
final BlockHeader parentHeader = final BlockHeader parentHeader =
@ -86,7 +86,7 @@ public class CliqueDifficultyValidationRuleTest {
@Test @Test
public void isTrueIfOutTurnValidatorSuppliesDifficultyOfOne() { public void isTrueIfOutTurnValidatorSuppliesDifficultyOfOne() {
final long OUT_OF_TURN_BLOCK_NUMBER = validatorList.size() - 1L; final long OUT_OF_TURN_BLOCK_NUMBER = validatorList.size() - 1L;
final UInt256 REPORTED_DIFFICULTY = UInt256.ONE; final Difficulty REPORTED_DIFFICULTY = Difficulty.ONE;
blockHeaderBuilder.number(OUT_OF_TURN_BLOCK_NUMBER - 1L); blockHeaderBuilder.number(OUT_OF_TURN_BLOCK_NUMBER - 1L);
final BlockHeader parentHeader = final BlockHeader parentHeader =
@ -105,7 +105,7 @@ public class CliqueDifficultyValidationRuleTest {
@Test @Test
public void isFalseIfOutTurnValidatorSuppliesDifficultyOfTwo() { public void isFalseIfOutTurnValidatorSuppliesDifficultyOfTwo() {
final long OUT_OF_TURN_BLOCK_NUMBER = validatorList.size() - 1L; final long OUT_OF_TURN_BLOCK_NUMBER = validatorList.size() - 1L;
final UInt256 REPORTED_DIFFICULTY = UInt256.valueOf(2); final Difficulty REPORTED_DIFFICULTY = Difficulty.of(2);
blockHeaderBuilder.number(OUT_OF_TURN_BLOCK_NUMBER - 1L); blockHeaderBuilder.number(OUT_OF_TURN_BLOCK_NUMBER - 1L);
final BlockHeader parentHeader = final BlockHeader parentHeader =
@ -125,7 +125,7 @@ public class CliqueDifficultyValidationRuleTest {
@Test @Test
public void isFalseIfInTurnValidatorSuppliesDifficultyOfOne() { public void isFalseIfInTurnValidatorSuppliesDifficultyOfOne() {
final long IN_TURN_BLOCK_NUMBER = validatorList.size(); final long IN_TURN_BLOCK_NUMBER = validatorList.size();
final UInt256 REPORTED_DIFFICULTY = UInt256.ONE; final Difficulty REPORTED_DIFFICULTY = Difficulty.ONE;
blockHeaderBuilder.number(IN_TURN_BLOCK_NUMBER - 1L); blockHeaderBuilder.number(IN_TURN_BLOCK_NUMBER - 1L);
final BlockHeader parentHeader = final BlockHeader parentHeader =

@ -60,6 +60,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters;
import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.core.Util;
@ -85,7 +86,6 @@ import java.util.stream.Collectors;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
public class TestContextBuilder { public class TestContextBuilder {
@ -240,7 +240,7 @@ public class TestContextBuilder {
Bytes.wrap(new byte[32]), Collections.emptyList(), Optional.empty(), 0, validators); Bytes.wrap(new byte[32]), Collections.emptyList(), Optional.empty(), 0, validators);
headerTestFixture.extraData(extraData.encode()); headerTestFixture.extraData(extraData.encode());
headerTestFixture.mixHash(IbftHelpers.EXPECTED_MIX_HASH); headerTestFixture.mixHash(IbftHelpers.EXPECTED_MIX_HASH);
headerTestFixture.difficulty(UInt256.ONE); headerTestFixture.difficulty(Difficulty.ONE);
headerTestFixture.ommersHash(Hash.EMPTY_LIST_HASH); headerTestFixture.ommersHash(Hash.EMPTY_LIST_HASH);
headerTestFixture.nonce(0); headerTestFixture.nonce(0);
headerTestFixture.timestamp(0); headerTestFixture.timestamp(0);

@ -54,7 +54,7 @@ public class IbftBlockHeaderValidationRulesetFactory {
"OmmersHash", BlockHeader::getOmmersHash, Hash.EMPTY_LIST_HASH)) "OmmersHash", BlockHeader::getOmmersHash, Hash.EMPTY_LIST_HASH))
.addRule( .addRule(
new ConstantFieldValidationRule<>( new ConstantFieldValidationRule<>(
"Difficulty", BlockHeader::internalGetDifficulty, UInt256.ONE)) "Difficulty", BlockHeader::getDifficulty, UInt256.ONE))
.addRule(new ConstantFieldValidationRule<>("Nonce", BlockHeader::getNonce, 0L)) .addRule(new ConstantFieldValidationRule<>("Nonce", BlockHeader::getNonce, 0L))
.addRule(new IbftValidatorsValidationRule()) .addRule(new IbftValidatorsValidationRule())
.addRule(new IbftCoinbaseValidationRule()) .addRule(new IbftCoinbaseValidationRule())

@ -24,6 +24,7 @@ import org.hyperledger.besu.crypto.SECP256K1.Signature;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.core.Util;
@ -120,7 +121,7 @@ public class IbftBlockHashingTest {
+ "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ "0000")); + "0000"));
builder.difficulty(UInt256.ONE); builder.difficulty(Difficulty.ONE);
builder.number(1); builder.number(1);
builder.gasLimit(4704588); builder.gasLimit(4704588);
builder.gasUsed(0); builder.gasUsed(0);

@ -24,6 +24,7 @@ import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.core.Util;
import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator; import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator;
@ -34,7 +35,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class IbftBlockHeaderValidationRulesetFactoryTest { public class IbftBlockHeaderValidationRulesetFactoryTest {
@ -211,7 +211,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
getPresetHeaderBuilder(1, proposerKeyPair, validators, null).buildHeader(); getPresetHeaderBuilder(1, proposerKeyPair, validators, null).buildHeader();
final BlockHeader blockHeader = final BlockHeader blockHeader =
getPresetHeaderBuilder(2, proposerKeyPair, validators, parentHeader) getPresetHeaderBuilder(2, proposerKeyPair, validators, parentHeader)
.difficulty(UInt256.valueOf(5)) .difficulty(Difficulty.of(5))
.buildHeader(); .buildHeader();
final BlockHeaderValidator<IbftContext> validator = final BlockHeaderValidator<IbftContext> validator =
@ -308,7 +308,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
Hash.fromHexString("0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365")); Hash.fromHexString("0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365"));
builder.ommersHash(Hash.EMPTY_LIST_HASH); builder.ommersHash(Hash.EMPTY_LIST_HASH);
builder.nonce(0); builder.nonce(0);
builder.difficulty(UInt256.ONE); builder.difficulty(Difficulty.ONE);
builder.coinbase(Util.publicKeyToAddress(proposerKeyPair.getPublicKey())); builder.coinbase(Util.publicKeyToAddress(proposerKeyPair.getPublicKey()));
final IbftExtraData ibftExtraData = final IbftExtraData ibftExtraData =

@ -149,7 +149,7 @@ public class IbftBlockHashing {
out.writeBytes(header.getTransactionsRoot()); out.writeBytes(header.getTransactionsRoot());
out.writeBytes(header.getReceiptsRoot()); out.writeBytes(header.getReceiptsRoot());
out.writeBytes(header.getLogsBloom().getBytes()); out.writeBytes(header.getLogsBloom().getBytes());
out.writeBytes(header.internalGetDifficulty().toMinimalBytes()); out.writeBytes(header.getDifficulty().toMinimalBytes());
out.writeLongScalar(header.getNumber()); out.writeLongScalar(header.getNumber());
out.writeLongScalar(header.getGasLimit()); out.writeLongScalar(header.getGasLimit());
out.writeLongScalar(header.getGasUsed()); out.writeLongScalar(header.getGasUsed());

@ -71,7 +71,7 @@ public class IbftBlockHeaderValidationRulesetFactory {
"OmmersHash", BlockHeader::getOmmersHash, Hash.EMPTY_LIST_HASH)) "OmmersHash", BlockHeader::getOmmersHash, Hash.EMPTY_LIST_HASH))
.addRule( .addRule(
new ConstantFieldValidationRule<>( new ConstantFieldValidationRule<>(
"Difficulty", BlockHeader::internalGetDifficulty, UInt256.ONE)) "Difficulty", BlockHeader::getDifficulty, UInt256.ONE))
.addRule(new VoteValidationRule()) .addRule(new VoteValidationRule())
.addRule(new IbftExtraDataValidationRule(validateCommitSeals)) .addRule(new IbftExtraDataValidationRule(validateCommitSeals))
.build(); .build();

@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
@ -26,7 +27,6 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.Test;
@ -117,7 +117,7 @@ public class IbftBlockHashingTest {
+ "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ "0000")); + "0000"));
builder.difficulty(UInt256.ONE); builder.difficulty(Difficulty.ONE);
builder.number(1); builder.number(1);
builder.gasLimit(4704588); builder.gasLimit(4704588);
builder.gasUsed(0); builder.gasUsed(0);

@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator; import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator;
import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode; import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode;
@ -40,7 +41,6 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class IbftBlockHeaderValidationRulesetFactoryTest { public class IbftBlockHeaderValidationRulesetFactoryTest {
@ -120,7 +120,7 @@ public class IbftBlockHeaderValidationRulesetFactoryTest {
Hash.fromHexString("0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365")); Hash.fromHexString("0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365"));
builder.ommersHash(Hash.EMPTY_LIST_HASH); builder.ommersHash(Hash.EMPTY_LIST_HASH);
builder.nonce(IbftLegacyBlockInterface.DROP_NONCE); builder.nonce(IbftLegacyBlockInterface.DROP_NONCE);
builder.difficulty(UInt256.ONE); builder.difficulty(Difficulty.ONE);
// Construct an extraData block // Construct an extraData block
final IbftExtraData initialIbftExtraData = final IbftExtraData initialIbftExtraData =

@ -44,6 +44,7 @@ import org.hyperledger.besu.ethereum.api.query.TransactionWithMetadata;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
@ -83,7 +84,7 @@ public class JsonRpcResponseUtils {
final Hash transactionsRoot = hash(values.get(TRANSACTION_ROOT)); final Hash transactionsRoot = hash(values.get(TRANSACTION_ROOT));
final Hash receiptsRoot = hash(values.get(RECEIPTS_ROOT)); final Hash receiptsRoot = hash(values.get(RECEIPTS_ROOT));
final LogsBloomFilter logsBloom = logsBloom(values.get(LOGS_BLOOM)); final LogsBloomFilter logsBloom = logsBloom(values.get(LOGS_BLOOM));
final UInt256 difficulty = unsignedInt256(values.get(DIFFICULTY)); final Difficulty difficulty = Difficulty.of(unsignedInt256(values.get(DIFFICULTY)));
final Bytes extraData = bytes(values.get(EXTRA_DATA)); final Bytes extraData = bytes(values.get(EXTRA_DATA));
final BlockHeaderFunctions blockHeaderFunctions = new MainnetBlockHeaderFunctions(); final BlockHeaderFunctions blockHeaderFunctions = new MainnetBlockHeaderFunctions();
final long number = unsignedLong(values.get(NUMBER)); final long number = unsignedLong(values.get(NUMBER));
@ -91,7 +92,7 @@ public class JsonRpcResponseUtils {
final long gasUsed = unsignedLong(values.get(GAS_USED)); final long gasUsed = unsignedLong(values.get(GAS_USED));
final long timestamp = unsignedLong(values.get(TIMESTAMP)); final long timestamp = unsignedLong(values.get(TIMESTAMP));
final long nonce = unsignedLong(values.get(NONCE)); final long nonce = unsignedLong(values.get(NONCE));
final UInt256 totalDifficulty = unsignedInt256(values.get(TOTAL_DIFFICULTY)); final Difficulty totalDifficulty = Difficulty.of(unsignedInt256(values.get(TOTAL_DIFFICULTY)));
final int size = unsignedInt(values.get(SIZE)); final int size = unsignedInt(values.get(SIZE));
final List<JsonNode> ommers = new ArrayList<>(); final List<JsonNode> ommers = new ArrayList<>();

@ -40,6 +40,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
@ -61,7 +62,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.assertj.core.util.Lists; import org.assertj.core.util.Lists;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -256,7 +256,7 @@ public class EthGetFilterChangesIntegrationTest {
} }
private Block appendBlock(final Transaction... transactionsToAdd) { private Block appendBlock(final Transaction... transactionsToAdd) {
return appendBlock(UInt256.ONE, getHeaderForCurrentChainHead(), transactionsToAdd); return appendBlock(Difficulty.ONE, getHeaderForCurrentChainHead(), transactionsToAdd);
} }
private BlockHeader getHeaderForCurrentChainHead() { private BlockHeader getHeaderForCurrentChainHead() {
@ -264,7 +264,7 @@ public class EthGetFilterChangesIntegrationTest {
} }
private Block appendBlock( private Block appendBlock(
final UInt256 difficulty, final Difficulty difficulty,
final BlockHeader parentBlock, final BlockHeader parentBlock,
final Transaction... transactionsToAdd) { final Transaction... transactionsToAdd) {
final List<Transaction> transactionList = asList(transactionsToAdd); final List<Transaction> transactionList = asList(transactionsToAdd);

@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.api.query.LogsQuery;
import org.hyperledger.besu.ethereum.api.query.TransactionWithMetadata; import org.hyperledger.besu.ethereum.api.query.TransactionWithMetadata;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogTopic; import org.hyperledger.besu.ethereum.core.LogTopic;
import org.hyperledger.besu.ethereum.core.LogWithMetadata; import org.hyperledger.besu.ethereum.core.LogWithMetadata;
@ -118,8 +119,8 @@ public class BlockAdapterBase extends AdapterBase {
return Optional.of(header.getMixHash()); return Optional.of(header.getMixHash());
} }
public Optional<UInt256> getDifficulty() { public Optional<Difficulty> getDifficulty() {
return Optional.of(header.internalGetDifficulty()); return Optional.of(header.getDifficulty());
} }
public Optional<Bytes32> getOmmerHash() { public Optional<Bytes32> getOmmerHash() {

@ -18,6 +18,7 @@ import org.hyperledger.besu.ethereum.api.query.BlockWithMetadata;
import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries;
import org.hyperledger.besu.ethereum.api.query.TransactionWithMetadata; import org.hyperledger.besu.ethereum.api.query.TransactionWithMetadata;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import java.util.ArrayList; import java.util.ArrayList;
@ -25,7 +26,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import graphql.schema.DataFetchingEnvironment; import graphql.schema.DataFetchingEnvironment;
import org.apache.tuweni.units.bigints.UInt256;
@SuppressWarnings("unused") // reflected by GraphQL @SuppressWarnings("unused") // reflected by GraphQL
public class NormalBlockAdapter extends BlockAdapterBase { public class NormalBlockAdapter extends BlockAdapterBase {
@ -42,7 +42,7 @@ public class NormalBlockAdapter extends BlockAdapterBase {
return Optional.of(blockWithMetaData.getTransactions().size()); return Optional.of(blockWithMetaData.getTransactions().size());
} }
public Optional<UInt256> getTotalDifficulty() { public Optional<Difficulty> getTotalDifficulty() {
return Optional.of(blockWithMetaData.getTotalDifficulty()); return Optional.of(blockWithMetaData.getTotalDifficulty());
} }

@ -15,6 +15,7 @@
package org.hyperledger.besu.ethereum.api.jsonrpc.internal.results; package org.hyperledger.besu.ethereum.api.jsonrpc.internal.results;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import java.util.List; import java.util.List;
@ -23,7 +24,6 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import org.apache.tuweni.units.bigints.UInt256;
@JsonPropertyOrder({ @JsonPropertyOrder({
"number", "number",
@ -73,7 +73,7 @@ public class BlockResult implements JsonRpcResult {
final BlockHeader header, final BlockHeader header,
final List<TransactionResult> transactions, final List<TransactionResult> transactions,
final List<JsonNode> ommers, final List<JsonNode> ommers,
final UInt256 totalDifficulty, final Difficulty totalDifficulty,
final int size) { final int size) {
this(header, transactions, ommers, totalDifficulty, size, false); this(header, transactions, ommers, totalDifficulty, size, false);
} }
@ -82,7 +82,7 @@ public class BlockResult implements JsonRpcResult {
final BlockHeader header, final BlockHeader header,
final List<TransactionResult> transactions, final List<TransactionResult> transactions,
final List<JsonNode> ommers, final List<JsonNode> ommers,
final UInt256 totalDifficulty, final Difficulty totalDifficulty,
final int size, final int size,
final boolean includeCoinbase) { final boolean includeCoinbase) {
this.number = Quantity.create(header.getNumber()); this.number = Quantity.create(header.getNumber());
@ -95,7 +95,7 @@ public class BlockResult implements JsonRpcResult {
this.stateRoot = header.getStateRoot().toString(); this.stateRoot = header.getStateRoot().toString();
this.receiptsRoot = header.getReceiptsRoot().toString(); this.receiptsRoot = header.getReceiptsRoot().toString();
this.miner = header.getCoinbase().toString(); this.miner = header.getCoinbase().toString();
this.difficulty = Quantity.create(header.internalGetDifficulty()); this.difficulty = Quantity.create(header.getDifficulty());
this.totalDifficulty = Quantity.create(totalDifficulty); this.totalDifficulty = Quantity.create(totalDifficulty);
this.extraData = header.getExtraData().toString(); this.extraData = header.getExtraData().toString();
this.size = Quantity.create(size); this.size = Quantity.create(size);

@ -17,11 +17,10 @@ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.results;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import java.util.Collections; import java.util.Collections;
import org.apache.tuweni.units.bigints.UInt256;
public class UncleBlockResult { public class UncleBlockResult {
/** /**
@ -34,6 +33,6 @@ public class UncleBlockResult {
final BlockBody body = new BlockBody(Collections.emptyList(), Collections.emptyList()); final BlockBody body = new BlockBody(Collections.emptyList(), Collections.emptyList());
final int size = new Block(header, body).calculateSize(); final int size = new Block(header, body).calculateSize();
return new BlockResult( return new BlockResult(
header, Collections.emptyList(), Collections.emptyList(), UInt256.ZERO, size); header, Collections.emptyList(), Collections.emptyList(), Difficulty.ZERO, size);
} }
} }

@ -15,17 +15,16 @@
package org.hyperledger.besu.ethereum.api.query; package org.hyperledger.besu.ethereum.api.query;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import java.util.List; import java.util.List;
import org.apache.tuweni.units.bigints.UInt256;
public class BlockWithMetadata<T, O> { public class BlockWithMetadata<T, O> {
private final BlockHeader header; private final BlockHeader header;
private final List<T> transactions; private final List<T> transactions;
private final List<O> ommers; private final List<O> ommers;
private final UInt256 totalDifficulty; private final Difficulty totalDifficulty;
private final int size; private final int size;
/** /**
@ -39,7 +38,7 @@ public class BlockWithMetadata<T, O> {
final BlockHeader header, final BlockHeader header,
final List<T> transactions, final List<T> transactions,
final List<O> ommers, final List<O> ommers,
final UInt256 totalDifficulty, final Difficulty totalDifficulty,
final int size) { final int size) {
this.header = header; this.header = header;
this.transactions = transactions; this.transactions = transactions;
@ -60,7 +59,7 @@ public class BlockWithMetadata<T, O> {
return transactions; return transactions;
} }
public UInt256 getTotalDifficulty() { public Difficulty getTotalDifficulty() {
return totalDifficulty; return totalDifficulty;
} }

@ -40,6 +40,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.DefaultSyncStatus; import org.hyperledger.besu.ethereum.core.DefaultSyncStatus;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters;
import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.core.Synchronizer;
@ -1722,7 +1723,7 @@ public class JsonRpcHttpServiceTest {
private void verifyBlockResult( private void verifyBlockResult(
final Block block, final Block block,
final UInt256 td, final Difficulty td,
final JsonObject result, final JsonObject result,
final boolean shouldTransactionsBeHashed) { final boolean shouldTransactionsBeHashed) {
assertBlockResultMatchesBlock(result, block); assertBlockResultMatchesBlock(result, block);
@ -1730,7 +1731,7 @@ public class JsonRpcHttpServiceTest {
if (td == null) { if (td == null) {
assertThat(result.getJsonObject("totalDifficulty")).isNull(); assertThat(result.getJsonObject("totalDifficulty")).isNull();
} else { } else {
assertThat(UInt256.fromHexString(result.getString("totalDifficulty"))).isEqualTo(td); assertThat(Difficulty.fromHexString(result.getString("totalDifficulty"))).isEqualTo(td);
} }
// Check ommers // Check ommers
@ -1812,8 +1813,8 @@ public class JsonRpcHttpServiceTest {
assertThat(Hash.fromHexString(result.getString("receiptsRoot"))) assertThat(Hash.fromHexString(result.getString("receiptsRoot")))
.isEqualTo(header.getReceiptsRoot()); .isEqualTo(header.getReceiptsRoot());
assertThat(Address.fromHexString(result.getString("miner"))).isEqualTo(header.getCoinbase()); assertThat(Address.fromHexString(result.getString("miner"))).isEqualTo(header.getCoinbase());
assertThat(UInt256.fromHexString(result.getString("difficulty"))) assertThat(Difficulty.fromHexString(result.getString("difficulty")))
.isEqualTo(header.internalGetDifficulty()); .isEqualTo(header.getDifficulty());
assertThat(Bytes.fromHexStringLenient(result.getString("extraData"))) assertThat(Bytes.fromHexStringLenient(result.getString("extraData")))
.isEqualTo(header.internalGetExtraData()); .isEqualTo(header.internalGetExtraData());
assertThat(hexStringToInt(result.getString("size"))).isEqualTo(block.calculateSize()); assertThat(hexStringToInt(result.getString("size"))).isEqualTo(block.calculateSize());
@ -1877,7 +1878,7 @@ public class JsonRpcHttpServiceTest {
} }
public BlockWithMetadata<TransactionWithMetadata, Hash> blockWithMetadata(final Block block) { public BlockWithMetadata<TransactionWithMetadata, Hash> blockWithMetadata(final Block block) {
final UInt256 td = block.getHeader().internalGetDifficulty().add(10L); final Difficulty td = block.getHeader().getDifficulty().add(10L);
final int size = block.calculateSize(); final int size = block.calculateSize();
final List<Transaction> txs = block.getBody().getTransactions(); final List<Transaction> txs = block.getBody().getTransactions();
@ -1893,7 +1894,7 @@ public class JsonRpcHttpServiceTest {
} }
public BlockWithMetadata<Hash, Hash> blockWithMetadataAndTxHashes(final Block block) { public BlockWithMetadata<Hash, Hash> blockWithMetadataAndTxHashes(final Block block) {
final UInt256 td = block.getHeader().internalGetDifficulty().add(10L); final Difficulty td = block.getHeader().getDifficulty().add(10L);
final int size = block.calculateSize(); final int size = block.calculateSize();
final List<Hash> txs = final List<Hash> txs =

@ -29,6 +29,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSucces
import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.ChainHead; import org.hyperledger.besu.ethereum.chain.ChainHead;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.peers.DefaultPeer; import org.hyperledger.besu.ethereum.p2p.peers.DefaultPeer;
@ -42,7 +43,6 @@ import java.util.Optional;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -61,7 +61,7 @@ public class AdminNodeInfoTest {
private final Bytes nodeId = private final Bytes nodeId =
Bytes.fromHexString( Bytes.fromHexString(
"0x0f1b319e32017c3fcb221841f0f978701b4e9513fe6a567a2db43d43381a9c7e3dfe7cae13cbc2f56943400bacaf9082576ab087cd51983b17d729ae796f6807"); "0x0f1b319e32017c3fcb221841f0f978701b4e9513fe6a567a2db43d43381a9c7e3dfe7cae13cbc2f56943400bacaf9082576ab087cd51983b17d729ae796f6807");
private final ChainHead testChainHead = new ChainHead(Hash.EMPTY, UInt256.ONE, 1L); private final ChainHead testChainHead = new ChainHead(Hash.EMPTY, Difficulty.ONE, 1L);
private final GenesisConfigOptions genesisConfigOptions = private final GenesisConfigOptions genesisConfigOptions =
new StubGenesisConfigOptions().chainId(BigInteger.valueOf(2019)); new StubGenesisConfigOptions().chainId(BigInteger.valueOf(2019));
private final DefaultPeer defaultPeer = private final DefaultPeer defaultPeer =

@ -34,6 +34,7 @@ import org.hyperledger.besu.ethereum.core.Account;
import org.hyperledger.besu.ethereum.core.AccountStorageEntry; import org.hyperledger.besu.ethereum.core.AccountStorageEntry;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.MutableWorldState;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
@ -93,7 +94,7 @@ public class DebugStorageRangeAtTest {
blockHeader, blockHeader,
Collections.singletonList(transactionWithMetadata), Collections.singletonList(transactionWithMetadata),
Collections.emptyList(), Collections.emptyList(),
UInt256.ONE, Difficulty.ONE,
1); 1);
final JsonRpcRequestContext request = final JsonRpcRequestContext request =
new JsonRpcRequestContext( new JsonRpcRequestContext(

@ -113,7 +113,7 @@ public class DebugTraceBlockTest {
parentBlock.getHeader(), parentBlock.getHeader(),
Collections.emptyList(), Collections.emptyList(),
Collections.emptyList(), Collections.emptyList(),
parentBlock.getHeader().internalGetDifficulty(), parentBlock.getHeader().getDifficulty(),
parentBlock.calculateSize()))); parentBlock.calculateSize())));
final JsonRpcSuccessResponse response = final JsonRpcSuccessResponse response =

@ -33,6 +33,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.TransactionTestFixture; import org.hyperledger.besu.ethereum.core.TransactionTestFixture;
@ -42,7 +43,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -150,7 +150,7 @@ public class EthGetUncleByBlockHashAndIndexTest {
header, header,
Collections.emptyList(), Collections.emptyList(),
Collections.emptyList(), Collections.emptyList(),
UInt256.ZERO, Difficulty.ZERO,
block.calculateSize()); block.calculateSize());
} }
@ -172,6 +172,6 @@ public class EthGetUncleByBlockHashAndIndexTest {
final List<Hash> ommers = new ArrayList<>(); final List<Hash> ommers = new ArrayList<>();
ommers.add(Hash.ZERO); ommers.add(Hash.ZERO);
return new BlockWithMetadata<>(header, transactions, ommers, header.internalGetDifficulty(), 0); return new BlockWithMetadata<>(header, transactions, ommers, header.getDifficulty(), 0);
} }
} }

@ -33,6 +33,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.TransactionTestFixture; import org.hyperledger.besu.ethereum.core.TransactionTestFixture;
@ -42,7 +43,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -126,7 +126,7 @@ public class EthGetUncleByBlockNumberAndIndexTest {
header, header,
Collections.emptyList(), Collections.emptyList(),
Collections.emptyList(), Collections.emptyList(),
UInt256.ZERO, Difficulty.ZERO,
block.calculateSize()); block.calculateSize());
} }
@ -148,6 +148,6 @@ public class EthGetUncleByBlockNumberAndIndexTest {
final List<Hash> ommers = new ArrayList<>(); final List<Hash> ommers = new ArrayList<>();
ommers.add(Hash.ZERO); ommers.add(Hash.ZERO);
return new BlockWithMetadata<>(header, transactions, ommers, header.internalGetDifficulty(), 0); return new BlockWithMetadata<>(header, transactions, ommers, header.getDifficulty(), 0);
} }
} }

@ -35,6 +35,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.TransactionTestFixture; import org.hyperledger.besu.ethereum.core.TransactionTestFixture;
@ -45,7 +46,6 @@ import java.util.Optional;
import java.util.function.Consumer; import java.util.function.Consumer;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -126,11 +126,7 @@ public class NewBlockHeadersSubscriptionServiceTest {
final List<TransactionWithMetadata> txHashList = transactionsWithMetadata(); final List<TransactionWithMetadata> txHashList = transactionsWithMetadata();
final BlockWithMetadata<TransactionWithMetadata, Hash> testBlockWithMetadata = final BlockWithMetadata<TransactionWithMetadata, Hash> testBlockWithMetadata =
new BlockWithMetadata<>( new BlockWithMetadata<>(
blockHeader, blockHeader, txHashList, Collections.emptyList(), blockHeader.getDifficulty(), 0);
txHashList,
Collections.emptyList(),
blockHeader.internalGetDifficulty(),
0);
final BlockResult expectedNewBlock = final BlockResult expectedNewBlock =
blockResultFactory.transactionComplete(testBlockWithMetadata); blockResultFactory.transactionComplete(testBlockWithMetadata);
when(blockchainQueries.blockByHash(testBlockWithMetadata.getHeader().getHash())) when(blockchainQueries.blockByHash(testBlockWithMetadata.getHeader().getHash()))
@ -178,7 +174,7 @@ public class NewBlockHeadersSubscriptionServiceTest {
private BlockResult expectedBlockWithTransactions(final List<Hash> objects) { private BlockResult expectedBlockWithTransactions(final List<Hash> objects) {
final BlockWithMetadata<Hash, Hash> testBlockWithMetadata = final BlockWithMetadata<Hash, Hash> testBlockWithMetadata =
new BlockWithMetadata<>(blockHeader, objects, Collections.emptyList(), UInt256.ONE, 1); new BlockWithMetadata<>(blockHeader, objects, Collections.emptyList(), Difficulty.ONE, 1);
final BlockResult expectedNewBlock = blockResultFactory.transactionHash(testBlockWithMetadata); final BlockResult expectedNewBlock = blockResultFactory.transactionHash(testBlockWithMetadata);
when(blockchainQueries.blockByHashWithTxHashes(testBlockWithMetadata.getHeader().getHash())) when(blockchainQueries.blockByHashWithTxHashes(testBlockWithMetadata.getHeader().getHash()))

@ -28,6 +28,7 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.Log; import org.hyperledger.besu.ethereum.core.Log;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
@ -43,7 +44,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.ClassRule; import org.junit.ClassRule;
@ -104,7 +104,7 @@ public class BlockchainQueriesLogCacheTest {
Hash.EMPTY, Hash.EMPTY,
Hash.EMPTY, Hash.EMPTY,
testLogsBloomFilter, testLogsBloomFilter,
UInt256.ZERO, Difficulty.ZERO,
0, 0,
0, 0,
0, 0,

@ -333,7 +333,7 @@ public class BlockchainQueriesTest {
.setParentHash(data.blockchain.getBlockHashByNumber(commonAncestor).get()) .setParentHash(data.blockchain.getBlockHashByNumber(commonAncestor).get())
.setBlockNumber(forkBlock) .setBlockNumber(forkBlock)
.setDifficulty( .setDifficulty(
data.blockchain.getBlockHeader(forkBlock).get().internalGetDifficulty().add(10L)); data.blockchain.getBlockHeader(forkBlock).get().getDifficulty().add(10L));
final Block fork = gen.block(options); final Block fork = gen.block(options);
final List<TransactionReceipt> forkReceipts = gen.receipts(fork); final List<TransactionReceipt> forkReceipts = gen.receipts(fork);

@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.DefaultEvmAccount; import org.hyperledger.besu.ethereum.core.DefaultEvmAccount;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.MutableWorldState;
import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader; import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader;
@ -49,7 +50,6 @@ import com.google.common.collect.Lists;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
public abstract class AbstractBlockCreator<C> implements AsyncBlockCreator { public abstract class AbstractBlockCreator<C> implements AsyncBlockCreator {
@ -256,7 +256,7 @@ public abstract class AbstractBlockCreator<C> implements AsyncBlockCreator {
return BlockHeaderBuilder.create() return BlockHeaderBuilder.create()
.parentHash(parentHeader.getHash()) .parentHash(parentHeader.getHash())
.coinbase(coinbase) .coinbase(coinbase)
.difficulty(UInt256.valueOf(difficulty)) .difficulty(Difficulty.of(difficulty))
.number(newBlockNumber) .number(newBlockNumber)
.gasLimit(gasLimit) .gasLimit(gasLimit)
.timestamp(timestamp) .timestamp(timestamp)

@ -85,7 +85,7 @@ public class EthHashBlockCreator extends AbstractBlockCreator<Void> {
private EthHashSolverInputs generateNonceSolverInputs( private EthHashSolverInputs generateNonceSolverInputs(
final SealableBlockHeader sealableBlockHeader) { final SealableBlockHeader sealableBlockHeader) {
final BigInteger difficulty = sealableBlockHeader.internalGetDifficulty().toBigInteger(); final BigInteger difficulty = sealableBlockHeader.getDifficulty().toBigInteger();
final UInt256 target = final UInt256 target =
difficulty.equals(BigInteger.ONE) difficulty.equals(BigInteger.ONE)
? UInt256.MAX_VALUE ? UInt256.MAX_VALUE

@ -27,6 +27,7 @@ import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.AddressHelpers;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.InMemoryStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryStorageProvider;
import org.hyperledger.besu.ethereum.core.LogSeries; import org.hyperledger.besu.ethereum.core.LogSeries;
@ -59,7 +60,6 @@ import java.util.function.Supplier;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.Test;
@ -83,7 +83,7 @@ public class BlockTransactionSelectorTest {
return BlockHeaderBuilder.create() return BlockHeaderBuilder.create()
.parentHash(Hash.EMPTY) .parentHash(Hash.EMPTY)
.coinbase(Address.fromHexString(String.format("%020x", 1))) .coinbase(Address.fromHexString(String.format("%020x", 1)))
.difficulty(UInt256.ONE) .difficulty(Difficulty.ONE)
.number(1) .number(1)
.gasLimit(gasLimit) .gasLimit(gasLimit)
.timestamp(Instant.now().toEpochMilli()) .timestamp(Instant.now().toEpochMilli())

@ -20,6 +20,7 @@ import org.hyperledger.besu.config.GenesisConfigFile;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.MutableWorldState;
@ -44,7 +45,6 @@ import java.util.function.Function;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class EthHashBlockCreatorTest { public class EthHashBlockCreatorTest {
@ -198,7 +198,7 @@ public class EthHashBlockCreatorTest {
BlockHeaderBuilder.create() BlockHeaderBuilder.create()
.parentHash(Hash.ZERO) .parentHash(Hash.ZERO)
.coinbase(BLOCK_1_COINBASE) .coinbase(BLOCK_1_COINBASE)
.difficulty(UInt256.ONE) .difficulty(Difficulty.ONE)
.number(1) .number(1)
.gasLimit(1) .gasLimit(1)
.timestamp(1) .timestamp(1)
@ -258,7 +258,7 @@ public class EthHashBlockCreatorTest {
BlockHeaderBuilder.create() BlockHeaderBuilder.create()
.parentHash(Hash.ZERO) .parentHash(Hash.ZERO)
.coinbase(BLOCK_1_COINBASE) .coinbase(BLOCK_1_COINBASE)
.difficulty(UInt256.ONE) .difficulty(Difficulty.ONE)
.number(1) .number(1)
.gasLimit(1) .gasLimit(1)
.timestamp(1) .timestamp(1)

@ -20,6 +20,7 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture;
import org.hyperledger.besu.ethereum.core.MessageFrameTestFixture; import org.hyperledger.besu.ethereum.core.MessageFrameTestFixture;
import org.hyperledger.besu.ethereum.vm.MessageFrame; import org.hyperledger.besu.ethereum.vm.MessageFrame;
@ -35,7 +36,6 @@ import java.nio.file.Path;
import com.google.common.io.MoreFiles; import com.google.common.io.MoreFiles;
import com.google.common.io.RecursiveDeleteOption; import com.google.common.io.RecursiveDeleteOption;
import org.apache.tuweni.units.bigints.UInt256;
public class OperationBenchmarkHelper { public class OperationBenchmarkHelper {
@ -70,7 +70,7 @@ public class OperationBenchmarkHelper {
new BlockHeaderTestFixture() new BlockHeaderTestFixture()
.parentHash(blockchain.getChainHeadHash()) .parentHash(blockchain.getChainHeadHash())
.number(i) .number(i)
.difficulty(UInt256.ONE) .difficulty(Difficulty.ONE)
.buildHeader(), .buildHeader(),
new BlockBody(emptyList(), emptyList())), new BlockBody(emptyList(), emptyList())),
emptyList()); emptyList());
@ -82,7 +82,7 @@ public class OperationBenchmarkHelper {
new BlockHeaderTestFixture() new BlockHeaderTestFixture()
.parentHash(blockchain.getChainHeadHash()) .parentHash(blockchain.getChainHeadHash())
.number(blockchain.getChainHeadBlockNumber() + 1) .number(blockchain.getChainHeadBlockNumber() + 1)
.difficulty(UInt256.ONE) .difficulty(Difficulty.ONE)
.buildHeader()) .buildHeader())
.build(); .build();
return new OperationBenchmarkHelper(storageDirectory, keyValueStorage, messageFrame); return new OperationBenchmarkHelper(storageDirectory, keyValueStorage, messageFrame);

@ -17,6 +17,7 @@ package org.hyperledger.besu.ethereum.chain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogWithMetadata; import org.hyperledger.besu.ethereum.core.LogWithMetadata;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
@ -26,8 +27,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.apache.tuweni.units.bigints.UInt256;
/** An interface for reading data from the blockchain. */ /** An interface for reading data from the blockchain. */
public interface Blockchain { public interface Blockchain {
/** /**
@ -160,7 +159,7 @@ public interface Blockchain {
* @param blockHeaderHash The hash of the block header being queried. * @param blockHeaderHash The hash of the block header being queried.
* @return The total difficulty of the corresponding block. * @return The total difficulty of the corresponding block.
*/ */
Optional<UInt256> getTotalDifficultyByHash(Hash blockHeaderHash); Optional<Difficulty> getTotalDifficultyByHash(Hash blockHeaderHash);
/** /**
* Given a transaction hash, returns the location (block number and transaction index) of the * Given a transaction hash, returns the location (block number and transaction index) of the

@ -16,6 +16,7 @@ package org.hyperledger.besu.ethereum.chain;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
@ -23,8 +24,6 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.units.bigints.UInt256;
public interface BlockchainStorage { public interface BlockchainStorage {
Optional<Hash> getChainHead(); Optional<Hash> getChainHead();
@ -39,7 +38,7 @@ public interface BlockchainStorage {
Optional<Hash> getBlockHash(long blockNumber); Optional<Hash> getBlockHash(long blockNumber);
Optional<UInt256> getTotalDifficulty(Hash blockHash); Optional<Difficulty> getTotalDifficulty(Hash blockHash);
Optional<TransactionLocation> getTransactionLocation(Hash transactionHash); Optional<TransactionLocation> getTransactionLocation(Hash transactionHash);
@ -57,7 +56,7 @@ public interface BlockchainStorage {
void putBlockHash(long blockNumber, Hash blockHash); void putBlockHash(long blockNumber, Hash blockHash);
void putTotalDifficulty(Hash blockHash, UInt256 totalDifficulty); void putTotalDifficulty(Hash blockHash, Difficulty totalDifficulty);
void setChainHead(Hash blockHash); void setChainHead(Hash blockHash);

@ -14,20 +14,19 @@
*/ */
package org.hyperledger.besu.ethereum.chain; package org.hyperledger.besu.ethereum.chain;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.apache.tuweni.units.bigints.UInt256;
/** Head of a blockchain. */ /** Head of a blockchain. */
public final class ChainHead { public final class ChainHead {
private final Hash hash; private final Hash hash;
private final UInt256 totalDifficulty; private final Difficulty totalDifficulty;
private final long height; private final long height;
public ChainHead(final Hash hash, final UInt256 totalDifficulty, final long height) { public ChainHead(final Hash hash, final Difficulty totalDifficulty, final long height) {
this.hash = hash; this.hash = hash;
this.totalDifficulty = totalDifficulty; this.totalDifficulty = totalDifficulty;
this.height = height; this.height = height;
@ -37,7 +36,7 @@ public final class ChainHead {
return hash; return hash;
} }
public UInt256 getTotalDifficulty() { public Difficulty getTotalDifficulty() {
return totalDifficulty; return totalDifficulty;
} }

@ -23,6 +23,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockWithReceipts; import org.hyperledger.besu.ethereum.core.BlockWithReceipts;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogWithMetadata; import org.hyperledger.besu.ethereum.core.LogWithMetadata;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
@ -46,7 +47,6 @@ import java.util.stream.Stream;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.tuweni.units.bigints.UInt256;
public class DefaultBlockchain implements MutableBlockchain { public class DefaultBlockchain implements MutableBlockchain {
@ -55,7 +55,7 @@ public class DefaultBlockchain implements MutableBlockchain {
private final Subscribers<BlockAddedObserver> blockAddedObservers = Subscribers.create(); private final Subscribers<BlockAddedObserver> blockAddedObservers = Subscribers.create();
private volatile BlockHeader chainHeader; private volatile BlockHeader chainHeader;
private volatile UInt256 totalDifficulty; private volatile Difficulty totalDifficulty;
private volatile int chainHeadTransactionCount; private volatile int chainHeadTransactionCount;
private volatile int chainHeadOmmerCount; private volatile int chainHeadOmmerCount;
@ -194,7 +194,7 @@ public class DefaultBlockchain implements MutableBlockchain {
} }
@Override @Override
public Optional<UInt256> getTotalDifficultyByHash(final Hash blockHeaderHash) { public Optional<Difficulty> getTotalDifficultyByHash(final Hash blockHeaderHash) {
return blockchainStorage.getTotalDifficulty(blockHeaderHash); return blockchainStorage.getTotalDifficulty(blockHeaderHash);
} }
@ -233,7 +233,7 @@ public class DefaultBlockchain implements MutableBlockchain {
final Block block = blockWithReceipts.getBlock(); final Block block = blockWithReceipts.getBlock();
final List<TransactionReceipt> receipts = blockWithReceipts.getReceipts(); final List<TransactionReceipt> receipts = blockWithReceipts.getReceipts();
final Hash hash = block.getHash(); final Hash hash = block.getHash();
final UInt256 td = calculateTotalDifficulty(block); final Difficulty td = calculateTotalDifficulty(block);
final BlockchainStorage.Updater updater = blockchainStorage.updater(); final BlockchainStorage.Updater updater = blockchainStorage.updater();
@ -254,23 +254,23 @@ public class DefaultBlockchain implements MutableBlockchain {
return blockAddedEvent; return blockAddedEvent;
} }
private UInt256 calculateTotalDifficulty(final Block block) { private Difficulty calculateTotalDifficulty(final Block block) {
if (block.getHeader().getNumber() == BlockHeader.GENESIS_BLOCK_NUMBER) { if (block.getHeader().getNumber() == BlockHeader.GENESIS_BLOCK_NUMBER) {
return block.getHeader().internalGetDifficulty(); return block.getHeader().getDifficulty();
} }
final UInt256 parentTotalDifficulty = final Difficulty parentTotalDifficulty =
blockchainStorage blockchainStorage
.getTotalDifficulty(block.getHeader().getParentHash()) .getTotalDifficulty(block.getHeader().getParentHash())
.orElseThrow( .orElseThrow(
() -> new IllegalStateException("Blockchain is missing total difficulty data.")); () -> new IllegalStateException("Blockchain is missing total difficulty data."));
return block.getHeader().internalGetDifficulty().add(parentTotalDifficulty); return block.getHeader().getDifficulty().add(parentTotalDifficulty);
} }
private BlockAddedEvent updateCanonicalChainData( private BlockAddedEvent updateCanonicalChainData(
final BlockchainStorage.Updater updater, final BlockchainStorage.Updater updater,
final BlockWithReceipts blockWithReceipts, final BlockWithReceipts blockWithReceipts,
final UInt256 totalDifficulty) { final Difficulty totalDifficulty) {
final Block newBlock = blockWithReceipts.getBlock(); final Block newBlock = blockWithReceipts.getBlock();
final Hash chainHead = blockchainStorage.getChainHead().orElse(null); final Hash chainHead = blockchainStorage.getChainHead().orElse(null);
if (newBlock.getHeader().getNumber() != BlockHeader.GENESIS_BLOCK_NUMBER && chainHead == null) { if (newBlock.getHeader().getNumber() != BlockHeader.GENESIS_BLOCK_NUMBER && chainHead == null) {
@ -430,7 +430,7 @@ public class DefaultBlockchain implements MutableBlockchain {
} }
} }
void updateCacheForNewCanonicalHead(final Block block, final UInt256 uInt256) { void updateCacheForNewCanonicalHead(final Block block, final Difficulty uInt256) {
chainHeader = block.getHeader(); chainHeader = block.getHeader();
totalDifficulty = uInt256; totalDifficulty = uInt256;
chainHeadTransactionCount = block.getBody().getTransactions().size(); chainHeadTransactionCount = block.getBody().getTransactions().size();

@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
import org.hyperledger.besu.ethereum.core.MutableAccount; import org.hyperledger.besu.ethereum.core.MutableAccount;
@ -189,8 +190,8 @@ public final class GenesisState {
return withNiceErrorMessage("extraData", genesis.getExtraData(), Bytes::fromHexString); return withNiceErrorMessage("extraData", genesis.getExtraData(), Bytes::fromHexString);
} }
private static UInt256 parseDifficulty(final GenesisConfigFile genesis) { private static Difficulty parseDifficulty(final GenesisConfigFile genesis) {
return withNiceErrorMessage("difficulty", genesis.getDifficulty(), UInt256::fromHexString); return withNiceErrorMessage("difficulty", genesis.getDifficulty(), Difficulty::fromHexString);
} }
private static Hash parseMixHash(final GenesisConfigFile genesis) { private static Hash parseMixHash(final GenesisConfigFile genesis) {

@ -22,7 +22,6 @@ import java.util.function.Supplier;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
/** A mined Ethereum block header. */ /** A mined Ethereum block header. */
public class BlockHeader extends SealableBlockHeader public class BlockHeader extends SealableBlockHeader
@ -48,7 +47,7 @@ public class BlockHeader extends SealableBlockHeader
final Hash transactionsRoot, final Hash transactionsRoot,
final Hash receiptsRoot, final Hash receiptsRoot,
final LogsBloomFilter logsBloom, final LogsBloomFilter logsBloom,
final UInt256 difficulty, final Difficulty difficulty,
final long number, final long number,
final long gasLimit, final long gasLimit,
final long gasUsed, final long gasUsed,
@ -159,7 +158,7 @@ public class BlockHeader extends SealableBlockHeader
Hash.wrap(input.readBytes32()), Hash.wrap(input.readBytes32()),
Hash.wrap(input.readBytes32()), Hash.wrap(input.readBytes32()),
LogsBloomFilter.readFrom(input), LogsBloomFilter.readFrom(input),
input.readUInt256Scalar(), Difficulty.of(input.readUInt256Scalar()),
input.readLongScalar(), input.readLongScalar(),
input.readLongScalar(), input.readLongScalar(),
input.readLongScalar(), input.readLongScalar(),
@ -224,7 +223,7 @@ public class BlockHeader extends SealableBlockHeader
Hash.fromHexString(pluginBlockHeader.getTransactionsRoot().getHexString()), Hash.fromHexString(pluginBlockHeader.getTransactionsRoot().getHexString()),
Hash.fromHexString(pluginBlockHeader.getReceiptsRoot().getHexString()), Hash.fromHexString(pluginBlockHeader.getReceiptsRoot().getHexString()),
LogsBloomFilter.fromHexString(pluginBlockHeader.getLogsBloom().getHexString()), LogsBloomFilter.fromHexString(pluginBlockHeader.getLogsBloom().getHexString()),
UInt256.fromHexString(pluginBlockHeader.getDifficulty().getHexString()), Difficulty.fromHexString(pluginBlockHeader.getDifficulty().getHexString()),
pluginBlockHeader.getNumber(), pluginBlockHeader.getNumber(),
pluginBlockHeader.getGasLimit(), pluginBlockHeader.getGasLimit(),
pluginBlockHeader.getGasUsed(), pluginBlockHeader.getGasUsed(),

@ -22,7 +22,6 @@ import java.time.Instant;
import java.util.OptionalLong; import java.util.OptionalLong;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
/** A utility class for building block headers. */ /** A utility class for building block headers. */
public class BlockHeaderBuilder { public class BlockHeaderBuilder {
@ -41,7 +40,7 @@ public class BlockHeaderBuilder {
private LogsBloomFilter logsBloom; private LogsBloomFilter logsBloom;
private UInt256 difficulty; private Difficulty difficulty;
private long number = -1L; private long number = -1L;
@ -74,7 +73,7 @@ public class BlockHeaderBuilder {
.transactionsRoot(header.getTransactionsRoot()) .transactionsRoot(header.getTransactionsRoot())
.receiptsRoot(header.getReceiptsRoot()) .receiptsRoot(header.getReceiptsRoot())
.logsBloom(header.getLogsBloom()) .logsBloom(header.getLogsBloom())
.difficulty(header.internalGetDifficulty()) .difficulty(header.getDifficulty())
.number(header.getNumber()) .number(header.getNumber())
.gasLimit(header.getGasLimit()) .gasLimit(header.getGasLimit())
.gasUsed(header.getGasUsed()) .gasUsed(header.getGasUsed())
@ -185,7 +184,7 @@ public class BlockHeaderBuilder {
checkNotNull(processableBlockHeader); checkNotNull(processableBlockHeader);
parentHash(processableBlockHeader.getParentHash()); parentHash(processableBlockHeader.getParentHash());
coinbase(processableBlockHeader.getCoinbase()); coinbase(processableBlockHeader.getCoinbase());
difficulty(processableBlockHeader.internalGetDifficulty()); difficulty(processableBlockHeader.getDifficulty());
number(processableBlockHeader.getNumber()); number(processableBlockHeader.getNumber());
gasLimit(processableBlockHeader.getGasLimit()); gasLimit(processableBlockHeader.getGasLimit());
timestamp(processableBlockHeader.getTimestamp()); timestamp(processableBlockHeader.getTimestamp());
@ -201,7 +200,7 @@ public class BlockHeaderBuilder {
transactionsRoot(sealableBlockHeader.getTransactionsRoot()); transactionsRoot(sealableBlockHeader.getTransactionsRoot());
receiptsRoot(sealableBlockHeader.getReceiptsRoot()); receiptsRoot(sealableBlockHeader.getReceiptsRoot());
logsBloom(sealableBlockHeader.getLogsBloom()); logsBloom(sealableBlockHeader.getLogsBloom());
difficulty(sealableBlockHeader.internalGetDifficulty()); difficulty(sealableBlockHeader.getDifficulty());
number(sealableBlockHeader.getNumber()); number(sealableBlockHeader.getNumber());
gasLimit(sealableBlockHeader.getGasLimit()); gasLimit(sealableBlockHeader.getGasLimit());
gasUsed(sealableBlockHeader.getGasUsed()); gasUsed(sealableBlockHeader.getGasUsed());
@ -252,7 +251,7 @@ public class BlockHeaderBuilder {
return this; return this;
} }
public BlockHeaderBuilder difficulty(final UInt256 difficulty) { public BlockHeaderBuilder difficulty(final Difficulty difficulty) {
checkNotNull(difficulty); checkNotNull(difficulty);
this.difficulty = difficulty; this.difficulty = difficulty;
return this; return this;

@ -0,0 +1,94 @@
/*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.core;
import org.hyperledger.besu.plugin.data.Quantity;
import java.math.BigInteger;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.BaseUInt256Value;
import org.apache.tuweni.units.bigints.UInt256;
/** A particular quantity of difficulty, the block difficulty to create new blocks. */
public final class Difficulty extends BaseUInt256Value<Difficulty> implements Quantity {
public static final Difficulty ZERO = of(0);
public static final Difficulty ONE = of(1);
public static final Difficulty MAX_VALUE = wrap(Bytes32.ZERO.not());
protected Difficulty(final UInt256 value) {
super(value, Difficulty::new);
}
private Difficulty(final long v) {
this(UInt256.valueOf(v));
}
private Difficulty(final BigInteger v) {
this(UInt256.valueOf(v));
}
private Difficulty(final String hexString) {
this(UInt256.fromHexString(hexString));
}
public static Difficulty of(final long value) {
return new Difficulty(value);
}
public static Difficulty of(final BigInteger value) {
return new Difficulty(value);
}
public static Difficulty of(final UInt256 value) {
return new Difficulty(value);
}
public static Difficulty wrap(final Bytes32 value) {
return new Difficulty(UInt256.fromBytes(value));
}
public static Difficulty fromHexString(final String str) {
return new Difficulty(str);
}
@Override
public Number getValue() {
return toBigInteger();
}
@Override
public byte[] getByteArray() {
return toBytes().toArray();
}
@Override
public String getHexString() {
return toHexString();
}
@Override
public int size() {
return toMinimalBytes().size();
}
@Override
public Difficulty copy() {
return super.copy();
}
}

@ -14,10 +14,6 @@
*/ */
package org.hyperledger.besu.ethereum.core; package org.hyperledger.besu.ethereum.core;
import org.hyperledger.besu.plugin.data.Quantity;
import org.apache.tuweni.units.bigints.UInt256;
/** A block header capable of being processed. */ /** A block header capable of being processed. */
public class ProcessableBlockHeader { public class ProcessableBlockHeader {
@ -25,7 +21,7 @@ public class ProcessableBlockHeader {
protected final Address coinbase; protected final Address coinbase;
protected final UInt256 difficulty; protected final Difficulty difficulty;
protected final long number; protected final long number;
@ -37,7 +33,7 @@ public class ProcessableBlockHeader {
protected ProcessableBlockHeader( protected ProcessableBlockHeader(
final Hash parentHash, final Hash parentHash,
final Address coinbase, final Address coinbase,
final UInt256 difficulty, final Difficulty difficulty,
final long number, final long number,
final long gasLimit, final long gasLimit,
final long timestamp) { final long timestamp) {
@ -72,11 +68,7 @@ public class ProcessableBlockHeader {
* *
* @return the block difficulty * @return the block difficulty
*/ */
public Quantity getDifficulty() { public Difficulty getDifficulty() {
return new QuantityWrapper(difficulty);
}
public UInt256 internalGetDifficulty() {
return difficulty; return difficulty;
} }

@ -1,48 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.core;
import org.hyperledger.besu.plugin.data.Quantity;
import org.apache.tuweni.units.bigints.UInt256;
public class QuantityWrapper implements Quantity {
private final UInt256 value;
public QuantityWrapper(final UInt256 value) {
this.value = value;
}
@Override
public Number getValue() {
return value.toBigInteger();
}
@Override
public byte[] getByteArray() {
return value.toBytes().toArrayUnsafe();
}
@Override
public String getHexString() {
return value.toHexString();
}
@Override
public int size() {
return value.toBytes().size();
}
}

@ -17,7 +17,6 @@ package org.hyperledger.besu.ethereum.core;
import org.hyperledger.besu.plugin.data.UnformattedData; import org.hyperledger.besu.plugin.data.UnformattedData;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
/** A block header capable of being sealed. */ /** A block header capable of being sealed. */
public class SealableBlockHeader extends ProcessableBlockHeader { public class SealableBlockHeader extends ProcessableBlockHeader {
@ -43,7 +42,7 @@ public class SealableBlockHeader extends ProcessableBlockHeader {
final Hash transactionsRoot, final Hash transactionsRoot,
final Hash receiptsRoot, final Hash receiptsRoot,
final LogsBloomFilter logsBloom, final LogsBloomFilter logsBloom,
final UInt256 difficulty, final Difficulty difficulty,
final long number, final long number,
final long gasLimit, final long gasLimit,
final long gasUsed, final long gasUsed,

@ -172,7 +172,7 @@ public final class EthHash {
out.writeBytes(header.getTransactionsRoot()); out.writeBytes(header.getTransactionsRoot());
out.writeBytes(header.getReceiptsRoot()); out.writeBytes(header.getReceiptsRoot());
out.writeBytes(header.getLogsBloom().getBytes()); out.writeBytes(header.getLogsBloom().getBytes());
out.writeUInt256Scalar(header.internalGetDifficulty()); out.writeUInt256Scalar(header.getDifficulty());
out.writeLongScalar(header.getNumber()); out.writeLongScalar(header.getNumber());
out.writeLongScalar(header.getGasLimit()); out.writeLongScalar(header.getGasLimit());
out.writeLongScalar(header.getGasUsed()); out.writeLongScalar(header.getGasUsed());

@ -36,7 +36,7 @@ public class CalculatedDifficultyValidationRule<C> implements AttachedBlockHeade
public boolean validate( public boolean validate(
final BlockHeader header, final BlockHeader parent, final ProtocolContext<C> context) { final BlockHeader header, final BlockHeader parent, final ProtocolContext<C> context) {
final BigInteger actualDifficulty = final BigInteger actualDifficulty =
new BigInteger(1, header.internalGetDifficulty().toBytes().toArray()); new BigInteger(1, header.getDifficulty().toBytes().toArray());
final BigInteger expectedDifficulty = final BigInteger expectedDifficulty =
difficultyCalculator.nextDifficulty(header.getTimestamp(), parent, context); difficultyCalculator.nextDifficulty(header.getTimestamp(), parent, context);

@ -42,11 +42,11 @@ public final class ProofOfWorkValidationRule implements DetachedBlockHeaderValid
final Hash headerHash = hashHeader(header); final Hash headerHash = hashHeader(header);
HASHER.hash(hashBuffer, header.getNonce(), header.getNumber(), headerHash.getByteArray()); HASHER.hash(hashBuffer, header.getNonce(), header.getNumber(), headerHash.getByteArray());
if (header.internalGetDifficulty().isZero()) { if (header.getDifficulty().isZero()) {
LOG.trace("Rejecting header because difficulty is 0"); LOG.trace("Rejecting header because difficulty is 0");
return false; return false;
} }
final BigInteger difficulty = header.internalGetDifficulty().toBytes().toUnsignedBigInteger(); final BigInteger difficulty = header.getDifficulty().toBytes().toUnsignedBigInteger();
final UInt256 target = final UInt256 target =
difficulty.equals(BigInteger.ONE) difficulty.equals(BigInteger.ONE)
? UInt256.MAX_VALUE ? UInt256.MAX_VALUE
@ -89,7 +89,7 @@ public final class ProofOfWorkValidationRule implements DetachedBlockHeaderValid
out.writeBytes(header.getTransactionsRoot()); out.writeBytes(header.getTransactionsRoot());
out.writeBytes(header.getReceiptsRoot()); out.writeBytes(header.getReceiptsRoot());
out.writeBytes(header.getLogsBloom().getBytes()); out.writeBytes(header.getLogsBloom().getBytes());
out.writeUInt256Scalar(header.internalGetDifficulty()); out.writeUInt256Scalar(header.getDifficulty());
out.writeLongScalar(header.getNumber()); out.writeLongScalar(header.getNumber());
out.writeLongScalar(header.getGasLimit()); out.writeLongScalar(header.getGasLimit());
out.writeLongScalar(header.getGasUsed()); out.writeLongScalar(header.getGasUsed());

@ -19,6 +19,7 @@ import org.hyperledger.besu.ethereum.chain.TransactionLocation;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.rlp.RLP; import org.hyperledger.besu.ethereum.rlp.RLP;
@ -94,8 +95,8 @@ public class KeyValueStoragePrefixedKeyBlockchainStorage implements BlockchainSt
} }
@Override @Override
public Optional<UInt256> getTotalDifficulty(final Hash blockHash) { public Optional<Difficulty> getTotalDifficulty(final Hash blockHash) {
return get(TOTAL_DIFFICULTY_PREFIX, blockHash).map(b -> UInt256.fromBytes(Bytes32.wrap(b, 0))); return get(TOTAL_DIFFICULTY_PREFIX, blockHash).map(b -> Difficulty.wrap(Bytes32.wrap(b, 0)));
} }
@Override @Override
@ -157,7 +158,7 @@ public class KeyValueStoragePrefixedKeyBlockchainStorage implements BlockchainSt
} }
@Override @Override
public void putTotalDifficulty(final Hash blockHash, final UInt256 totalDifficulty) { public void putTotalDifficulty(final Hash blockHash, final Difficulty totalDifficulty) {
set(TOTAL_DIFFICULTY_PREFIX, blockHash, totalDifficulty.toBytes()); set(TOTAL_DIFFICULTY_PREFIX, blockHash, totalDifficulty.toBytes());
} }

@ -14,13 +14,12 @@
*/ */
package org.hyperledger.besu.ethereum.vm.operations; package org.hyperledger.besu.ethereum.vm.operations;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Gas; import org.hyperledger.besu.ethereum.core.Gas;
import org.hyperledger.besu.ethereum.vm.AbstractOperation; import org.hyperledger.besu.ethereum.vm.AbstractOperation;
import org.hyperledger.besu.ethereum.vm.GasCalculator; import org.hyperledger.besu.ethereum.vm.GasCalculator;
import org.hyperledger.besu.ethereum.vm.MessageFrame; import org.hyperledger.besu.ethereum.vm.MessageFrame;
import org.apache.tuweni.units.bigints.UInt256;
public class DifficultyOperation extends AbstractOperation { public class DifficultyOperation extends AbstractOperation {
public DifficultyOperation(final GasCalculator gasCalculator) { public DifficultyOperation(final GasCalculator gasCalculator) {
@ -34,7 +33,7 @@ public class DifficultyOperation extends AbstractOperation {
@Override @Override
public void execute(final MessageFrame frame) { public void execute(final MessageFrame frame) {
final UInt256 difficulty = frame.getBlockHeader().internalGetDifficulty(); final Difficulty difficulty = frame.getBlockHeader().getDifficulty();
frame.pushStackItem(difficulty.toBytes()); frame.pushStackItem(difficulty.toBytes());
} }
} }

@ -260,7 +260,7 @@ public class BlockDataGenerator {
.transactionsRoot(hash()) .transactionsRoot(hash())
.receiptsRoot(hash()) .receiptsRoot(hash())
.logsBloom(logsBloom()) .logsBloom(logsBloom())
.difficulty(options.getDifficulty(uint256(4))) .difficulty(options.getDifficulty(Difficulty.of(uint256(4))))
.number(number) .number(number)
.gasLimit(gasLimit) .gasLimit(gasLimit)
.gasUsed(gasUsed) .gasUsed(gasUsed)
@ -486,7 +486,7 @@ public class BlockDataGenerator {
private OptionalLong blockNumber = OptionalLong.empty(); private OptionalLong blockNumber = OptionalLong.empty();
private Optional<Hash> parentHash = Optional.empty(); private Optional<Hash> parentHash = Optional.empty();
private Optional<Hash> stateRoot = Optional.empty(); private Optional<Hash> stateRoot = Optional.empty();
private Optional<UInt256> difficulty = Optional.empty(); private Optional<Difficulty> difficulty = Optional.empty();
private List<Transaction> transactions = new ArrayList<>(); private List<Transaction> transactions = new ArrayList<>();
private Optional<Bytes> extraData = Optional.empty(); private Optional<Bytes> extraData = Optional.empty();
private Optional<BlockHeaderFunctions> blockHeaderFunctions = Optional.empty(); private Optional<BlockHeaderFunctions> blockHeaderFunctions = Optional.empty();
@ -511,7 +511,7 @@ public class BlockDataGenerator {
return stateRoot.orElse(defaultValue); return stateRoot.orElse(defaultValue);
} }
public UInt256 getDifficulty(final UInt256 defaultValue) { public Difficulty getDifficulty(final Difficulty defaultValue) {
return difficulty.orElse(defaultValue); return difficulty.orElse(defaultValue);
} }
@ -547,7 +547,7 @@ public class BlockDataGenerator {
return this; return this;
} }
public BlockOptions setDifficulty(final UInt256 difficulty) { public BlockOptions setDifficulty(final Difficulty difficulty) {
this.difficulty = Optional.of(difficulty); this.difficulty = Optional.of(difficulty);
return this; return this;
} }

@ -17,7 +17,6 @@ package org.hyperledger.besu.ethereum.core;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions; import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
public class BlockHeaderTestFixture { public class BlockHeaderTestFixture {
@ -30,7 +29,7 @@ public class BlockHeaderTestFixture {
private Hash receiptsRoot = Hash.EMPTY_TRIE_HASH; private Hash receiptsRoot = Hash.EMPTY_TRIE_HASH;
private LogsBloomFilter logsBloom = LogsBloomFilter.empty(); private LogsBloomFilter logsBloom = LogsBloomFilter.empty();
private UInt256 difficulty = UInt256.ZERO; private Difficulty difficulty = Difficulty.ZERO;
private long number = 0; private long number = 0;
private long gasLimit = 0; private long gasLimit = 0;
@ -99,7 +98,7 @@ public class BlockHeaderTestFixture {
return this; return this;
} }
public BlockHeaderTestFixture difficulty(final UInt256 difficulty) { public BlockHeaderTestFixture difficulty(final Difficulty difficulty) {
this.difficulty = difficulty; this.difficulty = difficulty;
return this; return this;
} }

@ -20,6 +20,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogWithMetadata; import org.hyperledger.besu.ethereum.core.LogWithMetadata;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
@ -39,7 +40,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class DefaultBlockchainTest { public class DefaultBlockchainTest {
@ -265,7 +265,7 @@ public class DefaultBlockchainTest {
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(chain.get(commonAncestor).getHash()) .setParentHash(chain.get(commonAncestor).getHash())
.setBlockNumber(forkBlock) .setBlockNumber(forkBlock)
.setDifficulty(chain.get(forkBlock).getHeader().internalGetDifficulty().add(10L)); .setDifficulty(chain.get(forkBlock).getHeader().getDifficulty().add(10L));
final Block fork = gen.block(options); final Block fork = gen.block(options);
final List<TransactionReceipt> forkReceipts = gen.receipts(fork); final List<TransactionReceipt> forkReceipts = gen.receipts(fork);
final List<Block> reorgedChain = new ArrayList<>(chain.subList(0, forkBlock)); final List<Block> reorgedChain = new ArrayList<>(chain.subList(0, forkBlock));
@ -341,15 +341,15 @@ public class DefaultBlockchainTest {
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(chain.get(commonAncestor).getHash()) .setParentHash(chain.get(commonAncestor).getHash())
.setBlockNumber(forkStart) .setBlockNumber(forkStart)
.setDifficulty(chain.get(forkStart).getHeader().internalGetDifficulty().subtract(5L)); .setDifficulty(chain.get(forkStart).getHeader().getDifficulty().subtract(5L));
forkBlocks.add(gen.block(options)); forkBlocks.add(gen.block(options));
// Generate second block // Generate second block
final UInt256 remainingDifficultyToOutpace = final Difficulty remainingDifficultyToOutpace =
chain chain
.get(forkStart + 1) .get(forkStart + 1)
.getHeader() .getHeader()
.internalGetDifficulty() .getDifficulty()
.add(chain.get(forkStart + 2).getHeader().internalGetDifficulty()); .add(chain.get(forkStart + 2).getHeader().getDifficulty());
options = options =
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(forkBlocks.get(0).getHash()) .setParentHash(forkBlocks.get(0).getHash())
@ -461,14 +461,14 @@ public class DefaultBlockchainTest {
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(chain.get(commonAncestor).getHash()) .setParentHash(chain.get(commonAncestor).getHash())
.setBlockNumber(forkStart) .setBlockNumber(forkStart)
.setDifficulty(chain.get(forkStart).getHeader().internalGetDifficulty().subtract(5L)); .setDifficulty(chain.get(forkStart).getHeader().getDifficulty().subtract(5L));
forkBlocks.add(gen.block(options)); forkBlocks.add(gen.block(options));
// Generate second block // Generate second block
options = options =
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(forkBlocks.get(0).getHash()) .setParentHash(forkBlocks.get(0).getHash())
.setBlockNumber(forkStart + 1) .setBlockNumber(forkStart + 1)
.setDifficulty(UInt256.valueOf(10L)); .setDifficulty(Difficulty.of(10L));
forkBlocks.add(gen.block(options)); forkBlocks.add(gen.block(options));
// Generate corresponding receipts // Generate corresponding receipts
final List<List<TransactionReceipt>> forkReceipts = final List<List<TransactionReceipt>> forkReceipts =
@ -570,7 +570,7 @@ public class DefaultBlockchainTest {
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(chain.get(commonAncestor).getHash()) .setParentHash(chain.get(commonAncestor).getHash())
.setBlockNumber(forkBlock) .setBlockNumber(forkBlock)
.setDifficulty(chain.get(forkBlock).getHeader().internalGetDifficulty().add(10L)) .setDifficulty(chain.get(forkBlock).getHeader().getDifficulty().add(10L))
.addTransaction(overlappingTx) .addTransaction(overlappingTx)
.addTransaction(gen.transaction()); .addTransaction(gen.transaction());
final Block fork = gen.block(options); final Block fork = gen.block(options);
@ -683,15 +683,14 @@ public class DefaultBlockchainTest {
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(chain.get(commonAncestor).getHash()) .setParentHash(chain.get(commonAncestor).getHash())
.setBlockNumber(forkStart) .setBlockNumber(forkStart)
.setDifficulty(chain.get(forkStart).getHeader().internalGetDifficulty().subtract(5L)); .setDifficulty(chain.get(forkStart).getHeader().getDifficulty().subtract(5L));
forkBlocks.add(gen.block(options)); forkBlocks.add(gen.block(options));
// Generate second block // Generate second block
options = options =
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(forkBlocks.get(0).getHash()) .setParentHash(forkBlocks.get(0).getHash())
.setBlockNumber(forkStart + 1) .setBlockNumber(forkStart + 1)
.setDifficulty( .setDifficulty(chain.get(forkStart + 1).getHeader().getDifficulty().subtract(5L));
chain.get(forkStart + 1).getHeader().internalGetDifficulty().subtract(5L));
forkBlocks.add(gen.block(options)); forkBlocks.add(gen.block(options));
// Generate corresponding receipts // Generate corresponding receipts
final List<List<TransactionReceipt>> forkReceipts = final List<List<TransactionReceipt>> forkReceipts =
@ -725,7 +724,7 @@ public class DefaultBlockchainTest {
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setParentHash(chain.get(commonAncestor).getHash()) .setParentHash(chain.get(commonAncestor).getHash())
.setBlockNumber(forkStart) .setBlockNumber(forkStart)
.setDifficulty(chain.get(forkStart).getHeader().internalGetDifficulty().subtract(5L)); .setDifficulty(chain.get(forkStart).getHeader().getDifficulty().subtract(5L));
final Block secondFork = gen.block(options); final Block secondFork = gen.block(options);
blockchain.appendBlock(secondFork, gen.receipts(secondFork)); blockchain.appendBlock(secondFork, gen.receipts(secondFork));
@ -895,11 +894,11 @@ public class DefaultBlockchainTest {
private void assertTotalDifficultiesAreConsistent(final Blockchain blockchain, final Block head) { private void assertTotalDifficultiesAreConsistent(final Blockchain blockchain, final Block head) {
// Check that total difficulties are summed correctly // Check that total difficulties are summed correctly
long num = BlockHeader.GENESIS_BLOCK_NUMBER; long num = BlockHeader.GENESIS_BLOCK_NUMBER;
UInt256 td = UInt256.ZERO; Difficulty td = Difficulty.ZERO;
while (num <= head.getHeader().getNumber()) { while (num <= head.getHeader().getNumber()) {
final Hash curHash = blockchain.getBlockHashByNumber(num).get(); final Hash curHash = blockchain.getBlockHashByNumber(num).get();
final BlockHeader curHead = blockchain.getBlockHeader(curHash).get(); final BlockHeader curHead = blockchain.getBlockHeader(curHash).get();
td = td.add(curHead.internalGetDifficulty()); td = td.add(curHead.getDifficulty());
assertThat(blockchain.getTotalDifficultyByHash(curHash).get()).isEqualTo(td); assertThat(blockchain.getTotalDifficultyByHash(curHash).get()).isEqualTo(td);
num += 1; num += 1;

@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
/** A memory mock for testing. */ /** A memory mock for testing. */
@JsonIgnoreProperties("previousHash") @JsonIgnoreProperties("previousHash")
@ -49,7 +48,7 @@ public class BlockHeaderMock extends BlockHeader {
Hash.EMPTY, // transactionsRoot Hash.EMPTY, // transactionsRoot
Hash.EMPTY, // receiptsRoot Hash.EMPTY, // receiptsRoot
new LogsBloomFilter(), new LogsBloomFilter(),
UInt256.fromHexString(difficulty), Difficulty.fromHexString(difficulty),
Long.decode(number), Long.decode(number),
Long.decode(gasLimit), Long.decode(gasLimit),
0L, 0L,

@ -23,6 +23,7 @@ import org.hyperledger.besu.config.JsonUtil;
import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
@ -140,7 +141,7 @@ public class DifficultyCalculatorTests {
.nonce(0) .nonce(0)
.blockHeaderFunctions(blockHeaderFunctions) .blockHeaderFunctions(blockHeaderFunctions)
.timestamp(extractLong(value, "parentTimestamp")) .timestamp(extractLong(value, "parentTimestamp"))
.difficulty(UInt256.fromHexString(value.get("parentDifficulty").asText())) .difficulty(Difficulty.fromHexString(value.get("parentDifficulty").asText()))
.ommersHash(Hash.fromHexString(value.get("parentUncles").asText())) .ommersHash(Hash.fromHexString(value.get("parentUncles").asText()))
.number(currentBlockNumber) .number(currentBlockNumber)
.buildBlockHeader(); .buildBlockHeader();

@ -18,9 +18,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class ConstantFieldValidationRuleTest { public class ConstantFieldValidationRuleTest {
@ -45,17 +45,16 @@ public class ConstantFieldValidationRuleTest {
@Test @Test
public void difficultyFieldIsValidatedCorrectly() { public void difficultyFieldIsValidatedCorrectly() {
final ConstantFieldValidationRule<UInt256> uut = final ConstantFieldValidationRule<Difficulty> uut =
new ConstantFieldValidationRule<>( new ConstantFieldValidationRule<>("Difficulty", BlockHeader::getDifficulty, Difficulty.ONE);
"Difficulty", BlockHeader::internalGetDifficulty, UInt256.ONE);
final BlockHeaderTestFixture blockHeaderBuilder = new BlockHeaderTestFixture(); final BlockHeaderTestFixture blockHeaderBuilder = new BlockHeaderTestFixture();
blockHeaderBuilder.difficulty(UInt256.ONE); blockHeaderBuilder.difficulty(Difficulty.ONE);
BlockHeader header = blockHeaderBuilder.buildHeader(); BlockHeader header = blockHeaderBuilder.buildHeader();
assertThat(uut.validate(header, null)).isTrue(); assertThat(uut.validate(header, null)).isTrue();
blockHeaderBuilder.difficulty(UInt256.ZERO); blockHeaderBuilder.difficulty(Difficulty.ZERO);
header = blockHeaderBuilder.buildHeader(); header = blockHeaderBuilder.buildHeader();
assertThat(uut.validate(header, null)).isFalse(); assertThat(uut.validate(header, null)).isFalse();
} }

@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
@ -73,7 +74,7 @@ public class ProofOfWorkValidationRuleTest {
public void failsBlockWithZeroValuedDifficulty() { public void failsBlockWithZeroValuedDifficulty() {
final BlockHeader header = final BlockHeader header =
BlockHeaderBuilder.fromHeader(blockHeader) BlockHeaderBuilder.fromHeader(blockHeader)
.difficulty(UInt256.ZERO) .difficulty(Difficulty.ZERO)
.blockHeaderFunctions(mainnetBlockHashFunction()) .blockHeaderFunctions(mainnetBlockHashFunction())
.buildBlockHeader(); .buildBlockHeader();
assertThat(validationRule.validate(header, parentHeader)).isFalse(); assertThat(validationRule.validate(header, parentHeader)).isFalse();
@ -83,7 +84,7 @@ public class ProofOfWorkValidationRuleTest {
public void passesBlockWithOneValuedDifficulty() { public void passesBlockWithOneValuedDifficulty() {
final BlockHeaderBuilder headerBuilder = final BlockHeaderBuilder headerBuilder =
BlockHeaderBuilder.fromHeader(blockHeader) BlockHeaderBuilder.fromHeader(blockHeader)
.difficulty(UInt256.ONE) .difficulty(Difficulty.ONE)
.blockHeaderFunctions(mainnetBlockHashFunction()) .blockHeaderFunctions(mainnetBlockHashFunction())
.timestamp(1); .timestamp(1);
final BlockHeader preHeader = headerBuilder.buildBlockHeader(); final BlockHeader preHeader = headerBuilder.buildBlockHeader();
@ -102,7 +103,7 @@ public class ProofOfWorkValidationRuleTest {
@Test @Test
public void failsWithVeryLargeDifficulty() { public void failsWithVeryLargeDifficulty() {
final UInt256 largeDifficulty = UInt256.valueOf(BigInteger.valueOf(2).pow(255)); final Difficulty largeDifficulty = Difficulty.of(BigInteger.valueOf(2).pow(255));
final BlockHeader header = final BlockHeader header =
BlockHeaderBuilder.fromHeader(blockHeader) BlockHeaderBuilder.fromHeader(blockHeader)
.difficulty(largeDifficulty) .difficulty(largeDifficulty)

@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.InMemoryStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryStorageProvider;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
@ -31,7 +32,6 @@ import java.util.List;
import java.util.OptionalInt; import java.util.OptionalInt;
import java.util.Random; import java.util.Random;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
@ -97,7 +97,7 @@ public class BlockchainUtilParameterizedTest {
final BlockDataGenerator.BlockOptions remoteOptions = final BlockDataGenerator.BlockOptions remoteOptions =
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setDifficulty(UInt256.ONE) // differentiator .setDifficulty(Difficulty.ONE) // differentiator
.setBlockNumber(i) .setBlockNumber(i)
.setParentHash(remoteBlockchain.getBlockHashByNumber(i - 1).get()); .setParentHash(remoteBlockchain.getBlockHashByNumber(i - 1).get());
final Block remoteBlock = blockDataGenerator.block(remoteOptions); final Block remoteBlock = blockDataGenerator.block(remoteOptions);

@ -23,6 +23,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.InMemoryStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryStorageProvider;
import org.hyperledger.besu.ethereum.core.LogsBloomFilter; import org.hyperledger.besu.ethereum.core.LogsBloomFilter;
@ -41,7 +42,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
@JsonIgnoreProperties({"_info", "postState", "postStateHash"}) @JsonIgnoreProperties({"_info", "postState", "postStateHash"})
public class BlockchainReferenceTestCaseSpec { public class BlockchainReferenceTestCaseSpec {
@ -163,7 +163,7 @@ public class BlockchainReferenceTestCaseSpec {
Hash.fromHexString(transactionsTrie), // transactionsRoot Hash.fromHexString(transactionsTrie), // transactionsRoot
Hash.fromHexString(receiptTrie), // receiptTrie Hash.fromHexString(receiptTrie), // receiptTrie
LogsBloomFilter.fromHexString(bloom), // bloom LogsBloomFilter.fromHexString(bloom), // bloom
UInt256.fromHexString(difficulty), // difficulty Difficulty.fromHexString(difficulty), // difficulty
Long.decode(number), // number Long.decode(number), // number
Long.decode(gasLimit), // gasLimit Long.decode(gasLimit), // gasLimit
Long.decode(gasUsed), // gasUsed Long.decode(gasUsed), // gasUsed

@ -23,6 +23,7 @@ import org.hyperledger.besu.ethereum.chain.TransactionLocation;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
@ -33,7 +34,6 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
/** /**
* A blockchain mock for the Ethereum reference tests. * A blockchain mock for the Ethereum reference tests.
@ -128,7 +128,7 @@ public class TestBlockchain implements Blockchain {
} }
@Override @Override
public Optional<UInt256> getTotalDifficultyByHash(final Hash blockHeaderHash) { public Optional<Difficulty> getTotalDifficultyByHash(final Hash blockHeaderHash) {
// Deterministic, but just not implemented. // Deterministic, but just not implemented.
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }

@ -16,12 +16,11 @@
package org.hyperledger.besu.ethereum.eth.manager; package org.hyperledger.besu.ethereum.eth.manager;
import org.hyperledger.besu.ethereum.chain.ChainHead; import org.hyperledger.besu.ethereum.chain.ChainHead;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.apache.tuweni.units.bigints.UInt256;
public interface ChainHeadEstimate { public interface ChainHeadEstimate {
UInt256 getEstimatedTotalDifficulty(); Difficulty getEstimatedTotalDifficulty();
long getEstimatedHeight(); long getEstimatedHeight();

@ -15,11 +15,11 @@
package org.hyperledger.besu.ethereum.eth.manager; package org.hyperledger.besu.ethereum.eth.manager;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.util.Subscribers; import org.hyperledger.besu.util.Subscribers;
import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects;
import org.apache.tuweni.units.bigints.UInt256;
public class ChainState implements ChainHeadEstimate { public class ChainState implements ChainHeadEstimate {
// The best block by total difficulty that we know about // The best block by total difficulty that we know about
@ -53,7 +53,7 @@ public class ChainState implements ChainHeadEstimate {
} }
@Override @Override
public UInt256 getEstimatedTotalDifficulty() { public Difficulty getEstimatedTotalDifficulty() {
return bestBlock.getTotalDifficulty(); return bestBlock.getTotalDifficulty();
} }
@ -61,7 +61,7 @@ public class ChainState implements ChainHeadEstimate {
return bestBlock; return bestBlock;
} }
public void statusReceived(final Hash bestBlockHash, final UInt256 bestBlockTotalDifficulty) { public void statusReceived(final Hash bestBlockHash, final Difficulty bestBlockTotalDifficulty) {
synchronized (this) { synchronized (this) {
bestBlock.totalDifficulty = bestBlockTotalDifficulty; bestBlock.totalDifficulty = bestBlockTotalDifficulty;
bestBlock.hash = bestBlockHash; bestBlock.hash = bestBlockHash;
@ -87,11 +87,11 @@ public class ChainState implements ChainHeadEstimate {
} }
public void updateForAnnouncedBlock( public void updateForAnnouncedBlock(
final BlockHeader blockHeader, final UInt256 totalDifficulty) { final BlockHeader blockHeader, final Difficulty totalDifficulty) {
synchronized (this) { synchronized (this) {
// Blocks are announced before they're imported so their chain head must be the parent // Blocks are announced before they're imported so their chain head must be the parent
final UInt256 parentTotalDifficulty = final Difficulty parentTotalDifficulty =
totalDifficulty.subtract(blockHeader.internalGetDifficulty()); totalDifficulty.subtract(blockHeader.getDifficulty());
final long parentBlockNumber = blockHeader.getNumber() - 1; final long parentBlockNumber = blockHeader.getNumber() - 1;
if (parentTotalDifficulty.compareTo(bestBlock.totalDifficulty) >= 0) { if (parentTotalDifficulty.compareTo(bestBlock.totalDifficulty) >= 0) {
bestBlock.totalDifficulty = parentTotalDifficulty; bestBlock.totalDifficulty = parentTotalDifficulty;
@ -124,7 +124,7 @@ public class ChainState implements ChainHeadEstimate {
public static class BestBlock { public static class BestBlock {
volatile long number = 0L; volatile long number = 0L;
volatile Hash hash = null; volatile Hash hash = null;
volatile UInt256 totalDifficulty = UInt256.ZERO; volatile Difficulty totalDifficulty = Difficulty.ZERO;
public long getNumber() { public long getNumber() {
return number; return number;
@ -134,7 +134,7 @@ public class ChainState implements ChainHeadEstimate {
return hash; return hash;
} }
public UInt256 getTotalDifficulty() { public Difficulty getTotalDifficulty() {
return totalDifficulty; return totalDifficulty;
} }

@ -15,19 +15,19 @@
package org.hyperledger.besu.ethereum.eth.manager; package org.hyperledger.besu.ethereum.eth.manager;
import org.apache.tuweni.units.bigints.UInt256; import org.hyperledger.besu.ethereum.core.Difficulty;
public class ChainStateSnapshot implements ChainHeadEstimate { public class ChainStateSnapshot implements ChainHeadEstimate {
private final UInt256 totalDifficulty; private final Difficulty totalDifficulty;
private final long chainHeight; private final long chainHeight;
public ChainStateSnapshot(final UInt256 totalDifficulty, final long chainHeight) { public ChainStateSnapshot(final Difficulty totalDifficulty, final long chainHeight) {
this.totalDifficulty = totalDifficulty; this.totalDifficulty = totalDifficulty;
this.chainHeight = chainHeight; this.chainHeight = chainHeight;
} }
@Override @Override
public UInt256 getEstimatedTotalDifficulty() { public Difficulty getEstimatedTotalDifficulty() {
return totalDifficulty; return totalDifficulty;
} }

@ -16,6 +16,7 @@ package org.hyperledger.besu.ethereum.eth.manager;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.eth.messages.EthPV62; import org.hyperledger.besu.ethereum.eth.messages.EthPV62;
import org.hyperledger.besu.ethereum.eth.messages.EthPV63; import org.hyperledger.besu.ethereum.eth.messages.EthPV63;
@ -44,7 +45,6 @@ import java.util.function.Consumer;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
public class EthPeer { public class EthPeer {
private static final Logger LOG = LogManager.getLogger(); private static final Logger LOG = LogManager.getLogger();
@ -283,7 +283,7 @@ public class EthPeer {
maybeExecuteStatusesExchangedCallback(); maybeExecuteStatusesExchangedCallback();
} }
public void registerStatusReceived(final Hash hash, final UInt256 td) { public void registerStatusReceived(final Hash hash, final Difficulty td) {
chainHeadState.statusReceived(hash, td); chainHeadState.statusReceived(hash, td);
statusHasBeenReceivedFromPeer.set(true); statusHasBeenReceivedFromPeer.set(true);
maybeExecuteStatusesExchangedCallback(); maybeExecuteStatusesExchangedCallback();

@ -19,6 +19,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.MinedBlockObserver; import org.hyperledger.besu.ethereum.chain.MinedBlockObserver;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.eth.EthProtocol; import org.hyperledger.besu.ethereum.eth.EthProtocol;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
@ -48,7 +49,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.tuweni.units.bigints.UInt256;
public class EthProtocolManager implements ProtocolManager, MinedBlockObserver { public class EthProtocolManager implements ProtocolManager, MinedBlockObserver {
private static final Logger LOG = LogManager.getLogger(); private static final Logger LOG = LogManager.getLogger();
@ -305,7 +305,7 @@ public class EthProtocolManager implements ProtocolManager, MinedBlockObserver {
@Override @Override
public void blockMined(final Block block) { public void blockMined(final Block block) {
// This assumes the block has already been included in the chain // This assumes the block has already been included in the chain
final UInt256 totalDifficulty = final Difficulty totalDifficulty =
blockchain blockchain
.getTotalDifficultyByHash(block.getHash()) .getTotalDifficultyByHash(block.getHash())
.orElseThrow( .orElseThrow(

@ -16,6 +16,7 @@ package org.hyperledger.besu.ethereum.eth.messages;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions; import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.AbstractMessageData; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.AbstractMessageData;
@ -43,7 +44,7 @@ public class NewBlockMessage extends AbstractMessageData {
return MESSAGE_CODE; return MESSAGE_CODE;
} }
public static NewBlockMessage create(final Block block, final UInt256 totalDifficulty) { public static NewBlockMessage create(final Block block, final Difficulty totalDifficulty) {
final NewBlockMessageData msgData = new NewBlockMessageData(block, totalDifficulty); final NewBlockMessageData msgData = new NewBlockMessageData(block, totalDifficulty);
final BytesValueRLPOutput out = new BytesValueRLPOutput(); final BytesValueRLPOutput out = new BytesValueRLPOutput();
msgData.writeTo(out); msgData.writeTo(out);
@ -66,7 +67,7 @@ public class NewBlockMessage extends AbstractMessageData {
return messageFields(protocolSchedule).block(); return messageFields(protocolSchedule).block();
} }
public <C> UInt256 totalDifficulty(final ProtocolSchedule<C> protocolSchedule) { public <C> Difficulty totalDifficulty(final ProtocolSchedule<C> protocolSchedule) {
return messageFields(protocolSchedule).totalDifficulty(); return messageFields(protocolSchedule).totalDifficulty();
} }
@ -81,9 +82,9 @@ public class NewBlockMessage extends AbstractMessageData {
public static class NewBlockMessageData { public static class NewBlockMessageData {
private final Block block; private final Block block;
private final UInt256 totalDifficulty; private final Difficulty totalDifficulty;
public NewBlockMessageData(final Block block, final UInt256 totalDifficulty) { public NewBlockMessageData(final Block block, final Difficulty totalDifficulty) {
this.block = block; this.block = block;
this.totalDifficulty = totalDifficulty; this.totalDifficulty = totalDifficulty;
} }
@ -92,7 +93,7 @@ public class NewBlockMessage extends AbstractMessageData {
return block; return block;
} }
public UInt256 totalDifficulty() { public Difficulty totalDifficulty() {
return totalDifficulty; return totalDifficulty;
} }
@ -110,7 +111,7 @@ public class NewBlockMessage extends AbstractMessageData {
in.enterList(); in.enterList();
final Block block = Block.readFrom(in, blockHeaderFunctions); final Block block = Block.readFrom(in, blockHeaderFunctions);
final UInt256 totaldifficulty = in.readUInt256Scalar(); final UInt256 totaldifficulty = in.readUInt256Scalar();
return new NewBlockMessageData(block, totaldifficulty); return new NewBlockMessageData(block, Difficulty.of(totaldifficulty));
} }
} }
} }

@ -14,6 +14,7 @@
*/ */
package org.hyperledger.besu.ethereum.eth.messages; package org.hyperledger.besu.ethereum.eth.messages;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.AbstractMessageData; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.AbstractMessageData;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData;
@ -26,7 +27,6 @@ import java.math.BigInteger;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256;
public final class StatusMessage extends AbstractMessageData { public final class StatusMessage extends AbstractMessageData {
@ -39,7 +39,7 @@ public final class StatusMessage extends AbstractMessageData {
public static StatusMessage create( public static StatusMessage create(
final int protocolVersion, final int protocolVersion,
final BigInteger networkId, final BigInteger networkId,
final UInt256 totalDifficulty, final Difficulty totalDifficulty,
final Hash bestHash, final Hash bestHash,
final Hash genesisHash) { final Hash genesisHash) {
final EthStatus status = final EthStatus status =
@ -78,7 +78,7 @@ public final class StatusMessage extends AbstractMessageData {
} }
/** @return The total difficulty of the head of the associated node's local blockchain. */ /** @return The total difficulty of the head of the associated node's local blockchain. */
public UInt256 totalDifficulty() { public Difficulty totalDifficulty() {
return status().totalDifficulty; return status().totalDifficulty;
} }
@ -105,14 +105,14 @@ public final class StatusMessage extends AbstractMessageData {
private static class EthStatus { private static class EthStatus {
private final int protocolVersion; private final int protocolVersion;
private final BigInteger networkId; private final BigInteger networkId;
private final UInt256 totalDifficulty; private final Difficulty totalDifficulty;
private final Hash bestHash; private final Hash bestHash;
private final Hash genesisHash; private final Hash genesisHash;
EthStatus( EthStatus(
final int protocolVersion, final int protocolVersion,
final BigInteger networkId, final BigInteger networkId,
final UInt256 totalDifficulty, final Difficulty totalDifficulty,
final Hash bestHash, final Hash bestHash,
final Hash genesisHash) { final Hash genesisHash) {
this.protocolVersion = protocolVersion; this.protocolVersion = protocolVersion;
@ -139,7 +139,7 @@ public final class StatusMessage extends AbstractMessageData {
final int protocolVersion = in.readIntScalar(); final int protocolVersion = in.readIntScalar();
final BigInteger networkId = in.readBigIntegerScalar(); final BigInteger networkId = in.readBigIntegerScalar();
final UInt256 totalDifficulty = in.readUInt256Scalar(); final Difficulty totalDifficulty = Difficulty.of(in.readUInt256Scalar());
final Hash bestHash = Hash.wrap(in.readBytes32()); final Hash bestHash = Hash.wrap(in.readBytes32());
final Hash genesisHash = Hash.wrap(in.readBytes32()); final Hash genesisHash = Hash.wrap(in.readBytes32());

@ -15,6 +15,7 @@
package org.hyperledger.besu.ethereum.eth.sync; package org.hyperledger.besu.ethereum.eth.sync;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.messages.NewBlockMessage; import org.hyperledger.besu.ethereum.eth.messages.NewBlockMessage;
import org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection; import org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection;
@ -22,7 +23,6 @@ import org.hyperledger.besu.util.Subscribers;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.tuweni.units.bigints.UInt256;
public class BlockBroadcaster { public class BlockBroadcaster {
private static final Logger LOG = LogManager.getLogger(); private static final Logger LOG = LogManager.getLogger();
@ -43,7 +43,7 @@ public class BlockBroadcaster {
blockPropagatedSubscribers.unsubscribe(id); blockPropagatedSubscribers.unsubscribe(id);
} }
public void propagate(final Block block, final UInt256 totalDifficulty) { public void propagate(final Block block, final Difficulty totalDifficulty) {
blockPropagatedSubscribers.forEach(listener -> listener.accept(block, totalDifficulty)); blockPropagatedSubscribers.forEach(listener -> listener.accept(block, totalDifficulty));
final NewBlockMessage newBlockMessage = NewBlockMessage.create(block, totalDifficulty); final NewBlockMessage newBlockMessage = NewBlockMessage.create(block, totalDifficulty);
ethContext ethContext
@ -63,6 +63,6 @@ public class BlockBroadcaster {
@FunctionalInterface @FunctionalInterface
public interface BlockPropagatedSubscriber { public interface BlockPropagatedSubscriber {
void accept(Block block, UInt256 totalDifficulty); void accept(Block block, Difficulty totalDifficulty);
} }
} }

@ -20,6 +20,7 @@ import org.hyperledger.besu.ethereum.chain.BlockAddedEvent.EventType;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthMessage; import org.hyperledger.besu.ethereum.eth.manager.EthMessage;
@ -56,7 +57,6 @@ import com.google.common.collect.Lists;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.tuweni.units.bigints.UInt256;
public class BlockPropagationManager<C> { public class BlockPropagationManager<C> {
private static final Logger LOG = LogManager.getLogger(); private static final Logger LOG = LogManager.getLogger();
@ -155,7 +155,7 @@ public class BlockPropagationManager<C> {
final NewBlockMessage newBlockMessage = NewBlockMessage.readFrom(message.getData()); final NewBlockMessage newBlockMessage = NewBlockMessage.readFrom(message.getData());
try { try {
final Block block = newBlockMessage.block(protocolSchedule); final Block block = newBlockMessage.block(protocolSchedule);
final UInt256 totalDifficulty = newBlockMessage.totalDifficulty(protocolSchedule); final Difficulty totalDifficulty = newBlockMessage.totalDifficulty(protocolSchedule);
message.getPeer().chainState().updateForAnnouncedBlock(block.getHeader(), totalDifficulty); message.getPeer().chainState().updateForAnnouncedBlock(block.getHeader(), totalDifficulty);
@ -249,12 +249,12 @@ public class BlockPropagationManager<C> {
} }
private void broadcastBlock(final Block block, final BlockHeader parent) { private void broadcastBlock(final Block block, final BlockHeader parent) {
final UInt256 totalDifficulty = final Difficulty totalDifficulty =
protocolContext protocolContext
.getBlockchain() .getBlockchain()
.getTotalDifficultyByHash(parent.getHash()) .getTotalDifficultyByHash(parent.getHash())
.get() .get()
.add(block.getHeader().internalGetDifficulty()); .add(block.getHeader().getDifficulty());
blockBroadcaster.propagate(block, totalDifficulty); blockBroadcaster.propagate(block, totalDifficulty);
} }

@ -14,6 +14,7 @@
*/ */
package org.hyperledger.besu.ethereum.eth.sync.fullsync; package org.hyperledger.besu.ethereum.eth.sync.fullsync;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.manager.ChainState; import org.hyperledger.besu.ethereum.eth.manager.ChainState;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
import org.hyperledger.besu.ethereum.eth.manager.EthPeers; import org.hyperledger.besu.ethereum.eth.manager.EthPeers;
@ -21,8 +22,6 @@ import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.units.bigints.UInt256;
public class BetterSyncTargetEvaluator { public class BetterSyncTargetEvaluator {
private final SynchronizerConfiguration config; private final SynchronizerConfiguration config;
@ -48,7 +47,7 @@ public class BetterSyncTargetEvaluator {
// Require some threshold to be exceeded before switching targets to keep some // Require some threshold to be exceeded before switching targets to keep some
// stability when multiple peers are in range of each other // stability when multiple peers are in range of each other
final ChainState bestPeerChainState = bestPeer.chainState(); final ChainState bestPeerChainState = bestPeer.chainState();
final UInt256 tdDifference = final Difficulty tdDifference =
bestPeerChainState bestPeerChainState
.getEstimatedTotalDifficulty() .getEstimatedTotalDifficulty()
.subtract(currentPeerChainState.getBestBlock().getTotalDifficulty()); .subtract(currentPeerChainState.getBestBlock().getTotalDifficulty());

@ -23,14 +23,14 @@ import org.hyperledger.besu.ethereum.chain.ChainHead;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class ChainStateTest { public class ChainStateTest {
private static final UInt256 INITIAL_TOTAL_DIFFICULTY = UInt256.valueOf(256); private static final Difficulty INITIAL_TOTAL_DIFFICULTY = Difficulty.of(256);
private final ChainState chainState = new ChainState(); private final ChainState chainState = new ChainState();
@Test @Test
@ -184,7 +184,7 @@ public class ChainStateTest {
assertThat(chainState.getBestBlock().getNumber()).isEqualTo(0L); assertThat(chainState.getBestBlock().getNumber()).isEqualTo(0L);
final long betterBlockNumber = blockNumber + 2; final long betterBlockNumber = blockNumber + 2;
final UInt256 betterTd = INITIAL_TOTAL_DIFFICULTY.add(100L); final Difficulty betterTd = INITIAL_TOTAL_DIFFICULTY.add(100L);
final BlockHeader betterBlock = final BlockHeader betterBlock =
new BlockHeaderTestFixture().number(betterBlockNumber).buildHeader(); new BlockHeaderTestFixture().number(betterBlockNumber).buildHeader();
chainState.updateForAnnouncedBlock(betterBlock, betterTd); chainState.updateForAnnouncedBlock(betterBlock, betterTd);
@ -205,7 +205,7 @@ public class ChainStateTest {
assertThat(chainState.getBestBlock().getNumber()).isEqualTo(0L); assertThat(chainState.getBestBlock().getNumber()).isEqualTo(0L);
final long otherBlockNumber = blockNumber + 2; final long otherBlockNumber = blockNumber + 2;
final UInt256 otherTd = INITIAL_TOTAL_DIFFICULTY.subtract(100L); final Difficulty otherTd = INITIAL_TOTAL_DIFFICULTY.subtract(100L);
final BlockHeader otherBlock = final BlockHeader otherBlock =
new BlockHeaderTestFixture().number(otherBlockNumber).buildHeader(); new BlockHeaderTestFixture().number(otherBlockNumber).buildHeader();
chainState.updateForAnnouncedBlock(otherBlock, otherTd); chainState.updateForAnnouncedBlock(otherBlock, otherTd);
@ -228,7 +228,7 @@ public class ChainStateTest {
chainState.updateForAnnouncedBlock(bestBlockHeader, INITIAL_TOTAL_DIFFICULTY); chainState.updateForAnnouncedBlock(bestBlockHeader, INITIAL_TOTAL_DIFFICULTY);
final long otherBlockNumber = blockNumber - 2; final long otherBlockNumber = blockNumber - 2;
final UInt256 otherTd = INITIAL_TOTAL_DIFFICULTY.subtract(100L); final Difficulty otherTd = INITIAL_TOTAL_DIFFICULTY.subtract(100L);
final BlockHeader otherBlock = final BlockHeader otherBlock =
new BlockHeaderTestFixture().number(otherBlockNumber).buildHeader(); new BlockHeaderTestFixture().number(otherBlockNumber).buildHeader();
chainState.updateForAnnouncedBlock(otherBlock, otherTd); chainState.updateForAnnouncedBlock(otherBlock, otherTd);
@ -241,7 +241,7 @@ public class ChainStateTest {
@Test @Test
public void shouldOnlyHaveHeightEstimateWhenHeightHasBeenSet() { public void shouldOnlyHaveHeightEstimateWhenHeightHasBeenSet() {
chainState.statusReceived(Hash.EMPTY_LIST_HASH, UInt256.ONE); chainState.statusReceived(Hash.EMPTY_LIST_HASH, Difficulty.ONE);
assertThat(chainState.hasEstimatedHeight()).isFalse(); assertThat(chainState.hasEstimatedHeight()).isFalse();
chainState.update(new BlockHeaderTestFixture().number(12).buildHeader()); chainState.update(new BlockHeaderTestFixture().number(12).buildHeader());
@ -311,8 +311,8 @@ public class ChainStateTest {
@Test @Test
public void chainIsBetterThan_chainStateIsLighterAndShorter() { public void chainIsBetterThan_chainStateIsLighterAndShorter() {
final ChainState chainState = new ChainState(); final ChainState chainState = new ChainState();
updateChainState(chainState, UInt256.valueOf(50), 50); updateChainState(chainState, Difficulty.of(50), 50);
final ChainHead chainHead = new ChainHead(Hash.ZERO, UInt256.valueOf(100), 100); final ChainHead chainHead = new ChainHead(Hash.ZERO, Difficulty.of(100), 100);
assertThat(chainState.chainIsBetterThan(chainHead)).isFalse(); assertThat(chainState.chainIsBetterThan(chainHead)).isFalse();
} }
@ -320,8 +320,8 @@ public class ChainStateTest {
@Test @Test
public void chainIsBetterThan_chainStateIsHeavierAndShorter() { public void chainIsBetterThan_chainStateIsHeavierAndShorter() {
final ChainState chainState = new ChainState(); final ChainState chainState = new ChainState();
updateChainState(chainState, UInt256.valueOf(100), 50); updateChainState(chainState, Difficulty.of(100), 50);
final ChainHead chainHead = new ChainHead(Hash.ZERO, UInt256.valueOf(50), 100); final ChainHead chainHead = new ChainHead(Hash.ZERO, Difficulty.of(50), 100);
assertThat(chainState.chainIsBetterThan(chainHead)).isTrue(); assertThat(chainState.chainIsBetterThan(chainHead)).isTrue();
} }
@ -329,8 +329,8 @@ public class ChainStateTest {
@Test @Test
public void chainIsBetterThan_chainStateIsLighterAndTaller() { public void chainIsBetterThan_chainStateIsLighterAndTaller() {
final ChainState chainState = new ChainState(); final ChainState chainState = new ChainState();
updateChainState(chainState, UInt256.valueOf(50), 100); updateChainState(chainState, Difficulty.of(50), 100);
final ChainHead chainHead = new ChainHead(Hash.ZERO, UInt256.valueOf(100), 50); final ChainHead chainHead = new ChainHead(Hash.ZERO, Difficulty.of(100), 50);
assertThat(chainState.chainIsBetterThan(chainHead)).isTrue(); assertThat(chainState.chainIsBetterThan(chainHead)).isTrue();
} }
@ -338,8 +338,8 @@ public class ChainStateTest {
@Test @Test
public void chainIsBetterThan_chainStateIsHeavierAndTaller() { public void chainIsBetterThan_chainStateIsHeavierAndTaller() {
final ChainState chainState = new ChainState(); final ChainState chainState = new ChainState();
updateChainState(chainState, UInt256.valueOf(100), 100); updateChainState(chainState, Difficulty.of(100), 100);
final ChainHead chainHead = new ChainHead(Hash.ZERO, UInt256.valueOf(50), 50); final ChainHead chainHead = new ChainHead(Hash.ZERO, Difficulty.of(50), 50);
assertThat(chainState.chainIsBetterThan(chainHead)).isTrue(); assertThat(chainState.chainIsBetterThan(chainHead)).isTrue();
} }
@ -353,14 +353,14 @@ public class ChainStateTest {
* @param blockHeight The target estimated block height * @param blockHeight The target estimated block height
*/ */
private void updateChainState( private void updateChainState(
final ChainState chainState, final UInt256 totalDifficulty, final long blockHeight) { final ChainState chainState, final Difficulty totalDifficulty, final long blockHeight) {
// Chain state is updated based on the parent of the announced block // Chain state is updated based on the parent of the announced block
// So, increment block number by 1 and set block difficulty to zero // So, increment block number by 1 and set block difficulty to zero
// in order to update to the values we want // in order to update to the values we want
final BlockHeader header = final BlockHeader header =
new BlockHeaderTestFixture() new BlockHeaderTestFixture()
.number(blockHeight + 1L) .number(blockHeight + 1L)
.difficulty(UInt256.ZERO) .difficulty(Difficulty.ZERO)
.buildHeader(); .buildHeader();
chainState.updateForAnnouncedBlock(header, totalDifficulty); chainState.updateForAnnouncedBlock(header, totalDifficulty);

@ -24,6 +24,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.eth.manager.exceptions.NoAvailablePeersException; import org.hyperledger.besu.ethereum.eth.manager.exceptions.NoAvailablePeersException;
import org.hyperledger.besu.ethereum.eth.manager.exceptions.PeerDisconnectedException; import org.hyperledger.besu.ethereum.eth.manager.exceptions.PeerDisconnectedException;
@ -36,7 +37,6 @@ import java.util.OptionalLong;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -59,10 +59,10 @@ public class EthPeersTest {
public void comparesPeersWithHeightAndTd() { public void comparesPeersWithHeightAndTd() {
// Set peerA with better height, lower td // Set peerA with better height, lower td
final EthPeer peerA = final EthPeer peerA =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(50), 20) EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(50), 20)
.getEthPeer(); .getEthPeer();
final EthPeer peerB = final EthPeer peerB =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(100), 10) EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(100), 10)
.getEthPeer(); .getEthPeer();
assertThat(EthPeers.CHAIN_HEIGHT.compare(peerA, peerB)).isGreaterThan(0); assertThat(EthPeers.CHAIN_HEIGHT.compare(peerA, peerB)).isGreaterThan(0);
@ -82,11 +82,11 @@ public class EthPeersTest {
public void comparesPeersWithTdAndNoHeight() { public void comparesPeersWithTdAndNoHeight() {
final EthPeer peerA = final EthPeer peerA =
EthProtocolManagerTestUtil.createPeer( EthProtocolManagerTestUtil.createPeer(
ethProtocolManager, UInt256.valueOf(100), OptionalLong.empty()) ethProtocolManager, Difficulty.of(100), OptionalLong.empty())
.getEthPeer(); .getEthPeer();
final EthPeer peerB = final EthPeer peerB =
EthProtocolManagerTestUtil.createPeer( EthProtocolManagerTestUtil.createPeer(
ethProtocolManager, UInt256.valueOf(50), OptionalLong.empty()) ethProtocolManager, Difficulty.of(50), OptionalLong.empty())
.getEthPeer(); .getEthPeer();
// Sanity check // Sanity check

@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
@ -82,7 +83,6 @@ import java.util.stream.Collectors;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.awaitility.Awaitility; import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException; import org.awaitility.core.ConditionTimeoutException;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -968,7 +968,7 @@ public final class EthProtocolManagerTest {
blockchain.getBlockHeader(chainHeadHash).get(), blockchain.getBlockHeader(chainHeadHash).get(),
blockchain.getBlockBody(chainHeadHash).get()); blockchain.getBlockBody(chainHeadHash).get());
final UInt256 expectedTotalDifficulty = blockchain.getChainHead().getTotalDifficulty(); final Difficulty expectedTotalDifficulty = blockchain.getChainHead().getTotalDifficulty();
reset(onSend); reset(onSend);

@ -22,6 +22,7 @@ import org.hyperledger.besu.config.GenesisConfigFile;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.ChainHead; import org.hyperledger.besu.ethereum.chain.ChainHead;
import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.chain.GenesisState;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.EthProtocol; import org.hyperledger.besu.ethereum.eth.EthProtocol;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.DeterministicEthScheduler.TimeoutPolicy; import org.hyperledger.besu.ethereum.eth.manager.DeterministicEthScheduler.TimeoutPolicy;
@ -38,8 +39,6 @@ import java.math.BigInteger;
import java.util.Collections; import java.util.Collections;
import java.util.OptionalLong; import java.util.OptionalLong;
import org.apache.tuweni.units.bigints.UInt256;
public class EthProtocolManagerTestUtil { public class EthProtocolManagerTestUtil {
public static EthProtocolManager create( public static EthProtocolManager create(
@ -157,7 +156,7 @@ public class EthProtocolManagerTestUtil {
} }
public static RespondingEthPeer createPeer( public static RespondingEthPeer createPeer(
final EthProtocolManager ethProtocolManager, final UInt256 td) { final EthProtocolManager ethProtocolManager, final Difficulty td) {
return RespondingEthPeer.builder() return RespondingEthPeer.builder()
.ethProtocolManager(ethProtocolManager) .ethProtocolManager(ethProtocolManager)
.totalDifficulty(td) .totalDifficulty(td)
@ -165,7 +164,9 @@ public class EthProtocolManagerTestUtil {
} }
public static RespondingEthPeer createPeer( public static RespondingEthPeer createPeer(
final EthProtocolManager ethProtocolManager, final UInt256 td, final long estimatedHeight) { final EthProtocolManager ethProtocolManager,
final Difficulty td,
final long estimatedHeight) {
return RespondingEthPeer.builder() return RespondingEthPeer.builder()
.ethProtocolManager(ethProtocolManager) .ethProtocolManager(ethProtocolManager)
.totalDifficulty(td) .totalDifficulty(td)
@ -175,7 +176,7 @@ public class EthProtocolManagerTestUtil {
public static RespondingEthPeer createPeer( public static RespondingEthPeer createPeer(
final EthProtocolManager ethProtocolManager, final EthProtocolManager ethProtocolManager,
final UInt256 td, final Difficulty td,
final OptionalLong estimatedHeight) { final OptionalLong estimatedHeight) {
return RespondingEthPeer.builder() return RespondingEthPeer.builder()
.ethProtocolManager(ethProtocolManager) .ethProtocolManager(ethProtocolManager)
@ -186,7 +187,7 @@ public class EthProtocolManagerTestUtil {
public static RespondingEthPeer createPeer( public static RespondingEthPeer createPeer(
final EthProtocolManager ethProtocolManager, final EthProtocolManager ethProtocolManager,
final UInt256 td, final Difficulty td,
final OptionalLong estimatedHeight, final OptionalLong estimatedHeight,
final PeerValidator... validators) { final PeerValidator... validators) {
return RespondingEthPeer.builder() return RespondingEthPeer.builder()

@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.EthProtocol; import org.hyperledger.besu.ethereum.eth.EthProtocol;
@ -55,7 +56,6 @@ import java.util.stream.Stream;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
public class RespondingEthPeer { public class RespondingEthPeer {
private static final BlockDataGenerator gen = new BlockDataGenerator(); private static final BlockDataGenerator gen = new BlockDataGenerator();
@ -108,7 +108,7 @@ public class RespondingEthPeer {
private static RespondingEthPeer create( private static RespondingEthPeer create(
final EthProtocolManager ethProtocolManager, final EthProtocolManager ethProtocolManager,
final Hash chainHeadHash, final Hash chainHeadHash,
final UInt256 totalDifficulty, final Difficulty totalDifficulty,
final OptionalLong estimatedHeight, final OptionalLong estimatedHeight,
final List<PeerValidator> peerValidators) { final List<PeerValidator> peerValidators) {
final EthPeers ethPeers = ethProtocolManager.ethContext().getEthPeers(); final EthPeers ethPeers = ethProtocolManager.ethContext().getEthPeers();
@ -339,7 +339,7 @@ public class RespondingEthPeer {
public static class Builder { public static class Builder {
private EthProtocolManager ethProtocolManager; private EthProtocolManager ethProtocolManager;
private Hash chainHeadHash = gen.hash(); private Hash chainHeadHash = gen.hash();
private UInt256 totalDifficulty = UInt256.valueOf(1000L); private Difficulty totalDifficulty = Difficulty.of(1000L);
private OptionalLong estimatedHeight = OptionalLong.of(1000L); private OptionalLong estimatedHeight = OptionalLong.of(1000L);
private List<PeerValidator> peerValidators = new ArrayList<>(); private List<PeerValidator> peerValidators = new ArrayList<>();
@ -362,7 +362,7 @@ public class RespondingEthPeer {
return this; return this;
} }
public Builder totalDifficulty(final UInt256 totalDifficulty) { public Builder totalDifficulty(final Difficulty totalDifficulty) {
checkNotNull(totalDifficulty); checkNotNull(totalDifficulty);
this.totalDifficulty = totalDifficulty; this.totalDifficulty = totalDifficulty;
return this; return this;

@ -19,13 +19,13 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.RawMessage; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.RawMessage;
import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput; import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class NewBlockMessageTest { public class NewBlockMessageTest {
@ -33,7 +33,7 @@ public class NewBlockMessageTest {
@Test @Test
public void roundTripNewBlockMessage() { public void roundTripNewBlockMessage() {
final UInt256 totalDifficulty = UInt256.valueOf(98765); final Difficulty totalDifficulty = Difficulty.of(98765);
final BlockDataGenerator blockGenerator = new BlockDataGenerator(); final BlockDataGenerator blockGenerator = new BlockDataGenerator();
final Block blockForInsertion = blockGenerator.block(); final Block blockForInsertion = blockGenerator.block();
@ -46,7 +46,7 @@ public class NewBlockMessageTest {
@Test @Test
public void rawMessageUpCastsToANewBlockMessage() { public void rawMessageUpCastsToANewBlockMessage() {
final UInt256 totalDifficulty = UInt256.valueOf(12345); final Difficulty totalDifficulty = Difficulty.of(12345);
final BlockDataGenerator blockGenerator = new BlockDataGenerator(); final BlockDataGenerator blockGenerator = new BlockDataGenerator();
final Block blockForInsertion = blockGenerator.block(); final Block blockForInsertion = blockGenerator.block();

@ -16,6 +16,7 @@ package org.hyperledger.besu.ethereum.eth.messages;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.eth.EthProtocol; import org.hyperledger.besu.ethereum.eth.EthProtocol;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData;
@ -24,7 +25,6 @@ import java.math.BigInteger;
import java.util.Random; import java.util.Random;
import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class StatusMessageTest { public class StatusMessageTest {
@ -33,7 +33,7 @@ public class StatusMessageTest {
public void getters() { public void getters() {
final int version = EthProtocol.EthVersion.V62; final int version = EthProtocol.EthVersion.V62;
final BigInteger networkId = BigInteger.ONE; final BigInteger networkId = BigInteger.ONE;
final UInt256 td = UInt256.valueOf(1000L); final Difficulty td = Difficulty.of(1000L);
final Hash bestHash = randHash(1L); final Hash bestHash = randHash(1L);
final Hash genesisHash = randHash(2L); final Hash genesisHash = randHash(2L);
@ -50,7 +50,7 @@ public class StatusMessageTest {
public void serializeDeserialize() { public void serializeDeserialize() {
final int version = EthProtocol.EthVersion.V62; final int version = EthProtocol.EthVersion.V62;
final BigInteger networkId = BigInteger.ONE; final BigInteger networkId = BigInteger.ONE;
final UInt256 td = UInt256.valueOf(1000L); final Difficulty td = Difficulty.of(1000L);
final Hash bestHash = randHash(1L); final Hash bestHash = randHash(1L);
final Hash genesisHash = randHash(2L); final Hash genesisHash = randHash(2L);

@ -24,6 +24,7 @@ import static org.mockito.Mockito.when;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
import org.hyperledger.besu.ethereum.eth.manager.EthPeers; import org.hyperledger.besu.ethereum.eth.manager.EthPeers;
@ -33,7 +34,6 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection;
import java.util.Collections; import java.util.Collections;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Test; import org.junit.Test;
public class BlockBroadcasterTest { public class BlockBroadcasterTest {
@ -50,9 +50,9 @@ public class BlockBroadcasterTest {
final BlockBroadcaster blockBroadcaster = new BlockBroadcaster(ethContext); final BlockBroadcaster blockBroadcaster = new BlockBroadcaster(ethContext);
final Block block = generateBlock(); final Block block = generateBlock();
final NewBlockMessage newBlockMessage = final NewBlockMessage newBlockMessage =
NewBlockMessage.create(block, block.getHeader().internalGetDifficulty()); NewBlockMessage.create(block, block.getHeader().getDifficulty());
blockBroadcaster.propagate(block, UInt256.ZERO); blockBroadcaster.propagate(block, Difficulty.ZERO);
verify(ethPeer, times(1)).send(newBlockMessage); verify(ethPeer, times(1)).send(newBlockMessage);
} }
@ -73,9 +73,9 @@ public class BlockBroadcasterTest {
final BlockBroadcaster blockBroadcaster = new BlockBroadcaster(ethContext); final BlockBroadcaster blockBroadcaster = new BlockBroadcaster(ethContext);
final Block block = generateBlock(); final Block block = generateBlock();
final NewBlockMessage newBlockMessage = final NewBlockMessage newBlockMessage =
NewBlockMessage.create(block, block.getHeader().internalGetDifficulty()); NewBlockMessage.create(block, block.getHeader().getDifficulty());
blockBroadcaster.propagate(block, UInt256.ZERO); blockBroadcaster.propagate(block, Difficulty.ZERO);
verify(ethPeer0, never()).send(newBlockMessage); verify(ethPeer0, never()).send(newBlockMessage);
verify(ethPeer1, times(1)).send(newBlockMessage); verify(ethPeer1, times(1)).send(newBlockMessage);

@ -33,6 +33,7 @@ import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions; import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions;
import org.hyperledger.besu.ethereum.core.BlockImporter; import org.hyperledger.besu.ethereum.core.BlockImporter;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthMessages; import org.hyperledger.besu.ethereum.eth.manager.EthMessages;
import org.hyperledger.besu.ethereum.eth.manager.EthPeers; import org.hyperledger.besu.ethereum.eth.manager.EthPeers;
@ -55,7 +56,6 @@ import java.util.Collections;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
@ -496,7 +496,7 @@ public class BlockPropagationManagerTest {
// Setup peer and messages // Setup peer and messages
final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 0); final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 0);
final NewBlockMessage oldAnnouncement = NewBlockMessage.create(oldBlock, UInt256.ZERO); final NewBlockMessage oldAnnouncement = NewBlockMessage.create(oldBlock, Difficulty.ZERO);
// Broadcast // Broadcast
EthProtocolManagerTestUtil.broadcastMessage(ethProtocolManager, peer, oldAnnouncement); EthProtocolManagerTestUtil.broadcastMessage(ethProtocolManager, peer, oldAnnouncement);
@ -532,7 +532,8 @@ public class BlockPropagationManagerTest {
blockPropagationManager.start(); blockPropagationManager.start();
final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 0); final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 0);
final NewBlockMessage blockAnnouncementMsg = NewBlockMessage.create(blockToPurge, UInt256.ZERO); final NewBlockMessage blockAnnouncementMsg =
NewBlockMessage.create(blockToPurge, Difficulty.ZERO);
// Broadcast // Broadcast
EthProtocolManagerTestUtil.broadcastMessage(ethProtocolManager, peer, blockAnnouncementMsg); EthProtocolManagerTestUtil.broadcastMessage(ethProtocolManager, peer, blockAnnouncementMsg);
@ -566,9 +567,9 @@ public class BlockPropagationManagerTest {
// Setup peer and messages // Setup peer and messages
final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 0); final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 0);
final UInt256 parentTotalDifficulty = final Difficulty parentTotalDifficulty =
fullBlockchain.getTotalDifficultyByHash(nextBlock.getHeader().getParentHash()).get(); fullBlockchain.getTotalDifficultyByHash(nextBlock.getHeader().getParentHash()).get();
final UInt256 totalDifficulty = final Difficulty totalDifficulty =
fullBlockchain.getTotalDifficultyByHash(nextBlock.getHash()).get(); fullBlockchain.getTotalDifficultyByHash(nextBlock.getHash()).get();
final NewBlockMessage nextAnnouncement = NewBlockMessage.create(nextBlock, totalDifficulty); final NewBlockMessage nextAnnouncement = NewBlockMessage.create(nextBlock, totalDifficulty);
@ -623,7 +624,8 @@ public class BlockPropagationManagerTest {
// Setup peer and messages // Setup peer and messages
final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 0); final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 0);
final UInt256 totalDifficulty = fullBlockchain.getTotalDifficultyByHash(block.getHash()).get(); final Difficulty totalDifficulty =
fullBlockchain.getTotalDifficultyByHash(block.getHash()).get();
final NewBlockMessage newBlockMessage = NewBlockMessage.create(block, totalDifficulty); final NewBlockMessage newBlockMessage = NewBlockMessage.create(block, totalDifficulty);
// Broadcast message // Broadcast message

@ -19,6 +19,7 @@ import static org.mockito.Mockito.mock;
import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.GenesisConfigFile;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.difficulty.fixed.FixedDifficultyProtocolSchedule; import org.hyperledger.besu.ethereum.difficulty.fixed.FixedDifficultyProtocolSchedule;
import org.hyperledger.besu.ethereum.eth.manager.ChainState; import org.hyperledger.besu.ethereum.eth.manager.ChainState;
@ -29,7 +30,6 @@ import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.apache.tuweni.units.bigints.UInt256;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.Test;
@ -81,7 +81,7 @@ public class ChainHeadTrackerTest {
chainHeadTracker.onPeerConnected(respondingPeer.getEthPeer()); chainHeadTracker.onPeerConnected(respondingPeer.getEthPeer());
// Change the hash of the current known head // Change the hash of the current known head
respondingPeer.getEthPeer().chainState().statusReceived(Hash.EMPTY_TRIE_HASH, UInt256.ONE); respondingPeer.getEthPeer().chainState().statusReceived(Hash.EMPTY_TRIE_HASH, Difficulty.ONE);
respondingPeer.respond(responder); respondingPeer.respond(responder);

@ -27,6 +27,7 @@ import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.eth.manager.ChainState; import org.hyperledger.besu.ethereum.eth.manager.ChainState;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
@ -37,7 +38,6 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -155,7 +155,7 @@ public class TrailingPeerLimiterTest {
private EthPeer addPeerWithEstimatedHeight(final long height) { private EthPeer addPeerWithEstimatedHeight(final long height) {
final EthPeer peer = mock(EthPeer.class); final EthPeer peer = mock(EthPeer.class);
final ChainState chainState = new ChainState(); final ChainState chainState = new ChainState();
chainState.statusReceived(Hash.EMPTY, UInt256.ONE); chainState.statusReceived(Hash.EMPTY, Difficulty.ONE);
chainState.update(Hash.EMPTY, height); chainState.update(Hash.EMPTY, height);
when(peer.chainState()).thenReturn(chainState); when(peer.chainState()).thenReturn(chainState);
peers.add(peer); peers.add(peer);

@ -25,6 +25,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
@ -43,7 +44,6 @@ import java.util.OptionalLong;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -129,8 +129,8 @@ public class FastSyncActionsTest {
syncConfig = syncConfigBuilder.build(); syncConfig = syncConfigBuilder.build();
fastSyncActions = createFastSyncActions(syncConfig); fastSyncActions = createFastSyncActions(syncConfig);
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(1000), 5500); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(1000), 5500);
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(2000), 4000); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(2000), 4000);
final CompletableFuture<FastSyncState> result = final CompletableFuture<FastSyncState> result =
fastSyncActions.selectPivotBlock(FastSyncState.EMPTY_SYNC_STATE); fastSyncActions.selectPivotBlock(FastSyncState.EMPTY_SYNC_STATE);
@ -176,7 +176,7 @@ public class FastSyncActionsTest {
// Create peers without chain height estimates // Create peers without chain height estimates
List<RespondingEthPeer> peers = new ArrayList<>(); List<RespondingEthPeer> peers = new ArrayList<>();
for (int i = 0; i < minPeers; i++) { for (int i = 0; i < minPeers; i++) {
final UInt256 td = UInt256.valueOf(i); final Difficulty td = Difficulty.of(i);
final OptionalLong height = OptionalLong.empty(); final OptionalLong height = OptionalLong.empty();
final RespondingEthPeer peer = final RespondingEthPeer peer =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, td, height); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, td, height);
@ -222,7 +222,7 @@ public class FastSyncActionsTest {
final OptionalLong height = OptionalLong.of(minPivotHeight + 10); final OptionalLong height = OptionalLong.of(minPivotHeight + 10);
List<RespondingEthPeer> peers = new ArrayList<>(); List<RespondingEthPeer> peers = new ArrayList<>();
for (int i = 0; i < minPeers; i++) { for (int i = 0; i < minPeers; i++) {
final UInt256 td = UInt256.valueOf(i); final Difficulty td = Difficulty.of(i);
final RespondingEthPeer peer = final RespondingEthPeer peer =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, td, height, validator); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, td, height, validator);
@ -285,7 +285,7 @@ public class FastSyncActionsTest {
for (int i = 0; i < peerCount; i++) { for (int i = 0; i < peerCount; i++) {
// Best peer by td is the first peer, td decreases as i increases // Best peer by td is the first peer, td decreases as i increases
final boolean isBest = i == 0; final boolean isBest = i == 0;
final UInt256 td = UInt256.valueOf(peerCount - i); final Difficulty td = Difficulty.of(peerCount - i);
final OptionalLong height; final OptionalLong height;
if (isBest && bestMissingHeight) { if (isBest && bestMissingHeight) {

@ -25,6 +25,7 @@ import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@ -40,7 +41,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -215,11 +215,11 @@ public class PivotBlockRetrieverTest {
RespondingEthPeer.blockchainResponder(blockchain, protocolContext.getWorldStateArchive()); RespondingEthPeer.blockchainResponder(blockchain, protocolContext.getWorldStateArchive());
final RespondingEthPeer peerA = final RespondingEthPeer peerA =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(1000), 1000); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(1000), 1000);
final RespondingEthPeer peerB = final RespondingEthPeer peerB =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(500), 500); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(500), 500);
final RespondingEthPeer peerC = final RespondingEthPeer peerC =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(1000), 1000); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(1000), 1000);
final CompletableFuture<FastSyncState> future = pivotBlockRetriever.downloadPivotBlockHeader(); final CompletableFuture<FastSyncState> future = pivotBlockRetriever.downloadPivotBlockHeader();
@ -243,11 +243,11 @@ public class PivotBlockRetrieverTest {
final Responder emptyResponder = RespondingEthPeer.emptyResponder(); final Responder emptyResponder = RespondingEthPeer.emptyResponder();
final RespondingEthPeer peerA = final RespondingEthPeer peerA =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(1000), 1000); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(1000), 1000);
final RespondingEthPeer peerB = final RespondingEthPeer peerB =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(1000), 1000); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(1000), 1000);
final RespondingEthPeer peerC = final RespondingEthPeer peerC =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.valueOf(500), 500); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(500), 500);
final CompletableFuture<FastSyncState> future = pivotBlockRetriever.downloadPivotBlockHeader(); final CompletableFuture<FastSyncState> future = pivotBlockRetriever.downloadPivotBlockHeader();
peerA.respond(responder); peerA.respond(responder);

@ -18,6 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.eth.manager.ChainState; import org.hyperledger.besu.ethereum.eth.manager.ChainState;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
@ -152,7 +153,7 @@ public class BetterSyncTargetEvaluatorTest {
final EthPeer peer = mock(EthPeer.class); final EthPeer peer = mock(EthPeer.class);
final ChainState chainState = new ChainState(); final ChainState chainState = new ChainState();
chainState.updateHeightEstimate(chainHeight); chainState.updateHeightEstimate(chainHeight);
chainState.statusReceived(Hash.EMPTY, UInt256.valueOf(totalDifficulty)); chainState.statusReceived(Hash.EMPTY, Difficulty.of(totalDifficulty));
when(peer.chainState()).thenReturn(chainState); when(peer.chainState()).thenReturn(chainState);
return peer; return peer;
} }

@ -20,6 +20,7 @@ import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
@ -33,7 +34,6 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.Di
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -92,7 +92,7 @@ public class FullSyncChainDownloaderForkTest {
@Test @Test
public void disconnectsFromPeerOnBadFork() { public void disconnectsFromPeerOnBadFork() {
otherBlockchainSetup.importAllBlocks(); otherBlockchainSetup.importAllBlocks();
final UInt256 localTd = localBlockchain.getChainHead().getTotalDifficulty(); final Difficulty localTd = localBlockchain.getChainHead().getTotalDifficulty();
final RespondingEthPeer.Responder responder = final RespondingEthPeer.Responder responder =
RespondingEthPeer.blockchainResponder(otherBlockchain); RespondingEthPeer.blockchainResponder(otherBlockchain);

@ -26,6 +26,7 @@ import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
@ -49,7 +50,6 @@ import java.util.Optional;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Function; import java.util.function.Function;
import org.apache.tuweni.units.bigints.UInt256;
import org.awaitility.Awaitility; import org.awaitility.Awaitility;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@ -221,7 +221,8 @@ public class FullSyncChainDownloaderTest {
localBlockchainSetup.importFirstBlocks(3); localBlockchainSetup.importFirstBlocks(3);
gen = new BlockDataGenerator(); gen = new BlockDataGenerator();
final Block chainHead = localBlockchain.getChainHeadBlock(); final Block chainHead = localBlockchain.getChainHeadBlock();
final Block forkBlock = gen.block(gen.nextBlockOptions(chainHead).setDifficulty(UInt256.ZERO)); final Block forkBlock =
gen.block(gen.nextBlockOptions(chainHead).setDifficulty(Difficulty.ZERO));
localBlockchain.appendBlock(forkBlock, gen.receipts(forkBlock)); localBlockchain.appendBlock(forkBlock, gen.receipts(forkBlock));
// Sanity check // Sanity check
@ -251,7 +252,7 @@ public class FullSyncChainDownloaderTest {
@Test @Test
public void choosesBestPeerAsSyncTarget_byTd() { public void choosesBestPeerAsSyncTarget_byTd() {
final UInt256 localTd = localBlockchain.getChainHead().getTotalDifficulty(); final Difficulty localTd = localBlockchain.getChainHead().getTotalDifficulty();
final RespondingEthPeer.Responder responder = final RespondingEthPeer.Responder responder =
RespondingEthPeer.blockchainResponder(otherBlockchain); RespondingEthPeer.blockchainResponder(otherBlockchain);
@ -273,7 +274,7 @@ public class FullSyncChainDownloaderTest {
@Test @Test
public void choosesBestPeerAsSyncTarget_byTdAndHeight() { public void choosesBestPeerAsSyncTarget_byTdAndHeight() {
final UInt256 localTd = localBlockchain.getChainHead().getTotalDifficulty(); final Difficulty localTd = localBlockchain.getChainHead().getTotalDifficulty();
final RespondingEthPeer.Responder responder = final RespondingEthPeer.Responder responder =
RespondingEthPeer.blockchainResponder(otherBlockchain); RespondingEthPeer.blockchainResponder(otherBlockchain);

@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
@ -37,7 +38,6 @@ import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -88,7 +88,7 @@ public class FullSyncTargetManagerTest {
when(localWorldState.isWorldStateAvailable(localBlockchain.getChainHeadHeader().getStateRoot())) when(localWorldState.isWorldStateAvailable(localBlockchain.getChainHeadHeader().getStateRoot()))
.thenReturn(true); .thenReturn(true);
final RespondingEthPeer bestPeer = final RespondingEthPeer bestPeer =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.MAX_VALUE, 1); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.MAX_VALUE, 1);
final CompletableFuture<SyncTarget> result = syncTargetManager.findSyncTarget(Optional.empty()); final CompletableFuture<SyncTarget> result = syncTargetManager.findSyncTarget(Optional.empty());
bestPeer.respond(responder); bestPeer.respond(responder);
@ -103,7 +103,7 @@ public class FullSyncTargetManagerTest {
when(localWorldState.isWorldStateAvailable(localBlockchain.getChainHeadHeader().getStateRoot())) when(localWorldState.isWorldStateAvailable(localBlockchain.getChainHeadHeader().getStateRoot()))
.thenReturn(true); .thenReturn(true);
final RespondingEthPeer bestPeer = final RespondingEthPeer bestPeer =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager, UInt256.MAX_VALUE, 0); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.MAX_VALUE, 0);
final CompletableFuture<SyncTarget> result = syncTargetManager.findSyncTarget(Optional.empty()); final CompletableFuture<SyncTarget> result = syncTargetManager.findSyncTarget(Optional.empty());
bestPeer.respond(responder); bestPeer.respond(responder);

@ -32,6 +32,7 @@ import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions; import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.InMemoryStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryStorageProvider;
import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.core.Synchronizer;
import org.hyperledger.besu.ethereum.core.Synchronizer.InSyncListener; import org.hyperledger.besu.ethereum.core.Synchronizer.InSyncListener;
@ -50,7 +51,6 @@ import org.hyperledger.besu.plugin.services.BesuEvents.SyncStatusListener;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -61,13 +61,13 @@ import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class SyncStateTest { public class SyncStateTest {
private static final UInt256 standardDifficultyPerBlock = UInt256.ONE; private static final Difficulty standardDifficultyPerBlock = Difficulty.ONE;
private static final long OUR_CHAIN_HEAD_NUMBER = 20; private static final long OUR_CHAIN_HEAD_NUMBER = 20;
private static final UInt256 OUR_CHAIN_DIFFICULTY = private static final Difficulty OUR_CHAIN_DIFFICULTY =
standardDifficultyPerBlock.multiply(OUR_CHAIN_HEAD_NUMBER); standardDifficultyPerBlock.multiply(OUR_CHAIN_HEAD_NUMBER);
private static final long TARGET_CHAIN_DELTA = 20; private static final long TARGET_CHAIN_DELTA = 20;
private static final long TARGET_CHAIN_HEIGHT = OUR_CHAIN_HEAD_NUMBER + TARGET_CHAIN_DELTA; private static final long TARGET_CHAIN_HEIGHT = OUR_CHAIN_HEAD_NUMBER + TARGET_CHAIN_DELTA;
private static final UInt256 TARGET_DIFFICULTY = private static final Difficulty TARGET_DIFFICULTY =
standardDifficultyPerBlock.multiply(TARGET_CHAIN_HEIGHT); standardDifficultyPerBlock.multiply(TARGET_CHAIN_HEIGHT);
private final InSyncListener inSyncListener = mock(InSyncListener.class); private final InSyncListener inSyncListener = mock(InSyncListener.class);
@ -76,7 +76,7 @@ public class SyncStateTest {
private final BlockDataGenerator gen = new BlockDataGenerator(1); private final BlockDataGenerator gen = new BlockDataGenerator(1);
private final Block genesisBlock = private final Block genesisBlock =
gen.genesisBlock(new BlockOptions().setDifficulty(UInt256.ZERO)); gen.genesisBlock(new BlockOptions().setDifficulty(Difficulty.ZERO));
private final MutableBlockchain blockchain = private final MutableBlockchain blockchain =
InMemoryStorageProvider.createInMemoryBlockchain(genesisBlock); InMemoryStorageProvider.createInMemoryBlockchain(genesisBlock);
@ -95,7 +95,7 @@ public class SyncStateTest {
blockchain, InMemoryStorageProvider.createInMemoryWorldStateArchive()); blockchain, InMemoryStorageProvider.createInMemoryWorldStateArchive());
ethPeers = spy(ethProtocolManager.ethContext().getEthPeers()); ethPeers = spy(ethProtocolManager.ethContext().getEthPeers());
syncTargetPeer = createPeer(TARGET_DIFFICULTY, TARGET_CHAIN_HEIGHT); syncTargetPeer = createPeer(TARGET_DIFFICULTY, TARGET_CHAIN_HEIGHT);
otherPeer = createPeer(UInt256.ZERO, 0); otherPeer = createPeer(Difficulty.ZERO, 0);
advanceLocalChain(OUR_CHAIN_HEAD_NUMBER); advanceLocalChain(OUR_CHAIN_HEAD_NUMBER);
@ -561,7 +561,7 @@ public class SyncStateTest {
assertThat(clearedEvent).isEmpty(); assertThat(clearedEvent).isEmpty();
} }
private RespondingEthPeer createPeer(final UInt256 totalDifficulty, final long blockHeight) { private RespondingEthPeer createPeer(final Difficulty totalDifficulty, final long blockHeight) {
return EthProtocolManagerTestUtil.createPeer(ethProtocolManager, totalDifficulty, blockHeight); return EthProtocolManagerTestUtil.createPeer(ethProtocolManager, totalDifficulty, blockHeight);
} }
@ -614,14 +614,14 @@ public class SyncStateTest {
* @param totalDifficulty The total difficulty * @param totalDifficulty The total difficulty
*/ */
private void updateChainState( private void updateChainState(
final EthPeer peer, final long blockHeight, final UInt256 totalDifficulty) { final EthPeer peer, final long blockHeight, final Difficulty totalDifficulty) {
// Chain state is updated based on the parent of the announced block // Chain state is updated based on the parent of the announced block
// So, increment block number by 1 and set block difficulty to zero // So, increment block number by 1 and set block difficulty to zero
// in order to update to the values we want // in order to update to the values we want
final BlockHeader header = final BlockHeader header =
new BlockHeaderTestFixture() new BlockHeaderTestFixture()
.number(blockHeight + 1L) .number(blockHeight + 1L)
.difficulty(UInt256.ZERO) .difficulty(Difficulty.ZERO)
.buildHeader(); .buildHeader();
peer.chainState().updateForAnnouncedBlock(header, totalDifficulty); peer.chainState().updateForAnnouncedBlock(header, totalDifficulty);

@ -24,6 +24,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
@ -45,7 +46,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
@ -130,7 +130,7 @@ public class DetermineCommonAncestorTaskParameterizedTest {
final BlockDataGenerator.BlockOptions remoteOptions = final BlockDataGenerator.BlockOptions remoteOptions =
new BlockDataGenerator.BlockOptions() new BlockDataGenerator.BlockOptions()
.setDifficulty(UInt256.ONE) // differentiator .setDifficulty(Difficulty.ONE) // differentiator
.setBlockNumber(i) .setBlockNumber(i)
.setParentHash(remoteBlockchain.getBlockHashByNumber(i - 1).get()); .setParentHash(remoteBlockchain.getBlockHashByNumber(i - 1).get());
final Block remoteBlock = blockDataGenerator.block(remoteOptions); final Block remoteBlock = blockDataGenerator.block(remoteOptions);

@ -43,6 +43,7 @@ import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
@ -69,7 +70,6 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -185,8 +185,8 @@ public class TransactionPoolTest {
public void shouldNotRemovePendingTransactionsWhenABlockAddedToAFork() { public void shouldNotRemovePendingTransactionsWhenABlockAddedToAFork() {
transactions.addRemoteTransaction(transaction1); transactions.addRemoteTransaction(transaction1);
final BlockHeader commonParent = getHeaderForCurrentChainHead(); final BlockHeader commonParent = getHeaderForCurrentChainHead();
final Block canonicalHead = appendBlock(UInt256.valueOf(1000), commonParent); final Block canonicalHead = appendBlock(Difficulty.of(1000), commonParent);
appendBlock(UInt256.ONE, commonParent, transaction1); appendBlock(Difficulty.ONE, commonParent, transaction1);
verifyChainHeadIs(canonicalHead); verifyChainHeadIs(canonicalHead);
@ -198,13 +198,12 @@ public class TransactionPoolTest {
transactions.addRemoteTransaction(transaction1); transactions.addRemoteTransaction(transaction1);
transactions.addRemoteTransaction(transaction2); transactions.addRemoteTransaction(transaction2);
final BlockHeader commonParent = getHeaderForCurrentChainHead(); final BlockHeader commonParent = getHeaderForCurrentChainHead();
final Block originalChainHead = appendBlock(UInt256.valueOf(1000), commonParent); final Block originalChainHead = appendBlock(Difficulty.of(1000), commonParent);
final Block forkBlock1 = appendBlock(UInt256.ONE, commonParent, transaction1); final Block forkBlock1 = appendBlock(Difficulty.ONE, commonParent, transaction1);
verifyChainHeadIs(originalChainHead); verifyChainHeadIs(originalChainHead);
final Block forkBlock2 = final Block forkBlock2 = appendBlock(Difficulty.of(2000), forkBlock1.getHeader(), transaction2);
appendBlock(UInt256.valueOf(2000), forkBlock1.getHeader(), transaction2);
verifyChainHeadIs(forkBlock2); verifyChainHeadIs(forkBlock2);
assertTransactionNotPending(transaction1); assertTransactionNotPending(transaction1);
@ -218,16 +217,17 @@ public class TransactionPoolTest {
transactions.addRemoteTransaction(transaction1); transactions.addRemoteTransaction(transaction1);
transactions.addRemoteTransaction(transaction2); transactions.addRemoteTransaction(transaction2);
final BlockHeader commonParent = getHeaderForCurrentChainHead(); final BlockHeader commonParent = getHeaderForCurrentChainHead();
final Block originalFork1 = appendBlock(UInt256.valueOf(1000), commonParent, transaction1); final Block originalFork1 = appendBlock(Difficulty.of(1000), commonParent, transaction1);
final Block originalFork2 = appendBlock(UInt256.ONE, originalFork1.getHeader(), transaction2); final Block originalFork2 =
appendBlock(Difficulty.ONE, originalFork1.getHeader(), transaction2);
assertTransactionNotPending(transaction1); assertTransactionNotPending(transaction1);
assertTransactionNotPending(transaction2); assertTransactionNotPending(transaction2);
final Block reorgFork1 = appendBlock(UInt256.ONE, commonParent); final Block reorgFork1 = appendBlock(Difficulty.ONE, commonParent);
verifyChainHeadIs(originalFork2); verifyChainHeadIs(originalFork2);
transactions.subscribePendingTransactions(listener); transactions.subscribePendingTransactions(listener);
final Block reorgFork2 = appendBlock(UInt256.valueOf(2000), reorgFork1.getHeader()); final Block reorgFork2 = appendBlock(Difficulty.of(2000), reorgFork1.getHeader());
verifyChainHeadIs(reorgFork2); verifyChainHeadIs(reorgFork2);
assertTransactionPending(transaction1); assertTransactionPending(transaction1);
@ -244,15 +244,16 @@ public class TransactionPoolTest {
transactions.addRemoteTransaction(transaction1); transactions.addRemoteTransaction(transaction1);
transactions.addRemoteTransaction(transaction2); transactions.addRemoteTransaction(transaction2);
final BlockHeader commonParent = getHeaderForCurrentChainHead(); final BlockHeader commonParent = getHeaderForCurrentChainHead();
final Block originalFork1 = appendBlock(UInt256.valueOf(1000), commonParent, transaction1); final Block originalFork1 = appendBlock(Difficulty.of(1000), commonParent, transaction1);
final Block originalFork2 = appendBlock(UInt256.ONE, originalFork1.getHeader(), transaction2); final Block originalFork2 =
appendBlock(Difficulty.ONE, originalFork1.getHeader(), transaction2);
assertTransactionNotPending(transaction1); assertTransactionNotPending(transaction1);
assertTransactionNotPending(transaction2); assertTransactionNotPending(transaction2);
final Block reorgFork1 = appendBlock(UInt256.ONE, commonParent, transaction1); final Block reorgFork1 = appendBlock(Difficulty.ONE, commonParent, transaction1);
verifyChainHeadIs(originalFork2); verifyChainHeadIs(originalFork2);
final Block reorgFork2 = appendBlock(UInt256.valueOf(2000), reorgFork1.getHeader()); final Block reorgFork2 = appendBlock(Difficulty.of(2000), reorgFork1.getHeader());
verifyChainHeadIs(reorgFork2); verifyChainHeadIs(reorgFork2);
assertTransactionNotPending(transaction1); assertTransactionNotPending(transaction1);
@ -619,7 +620,7 @@ public class TransactionPoolTest {
} }
private void appendBlock(final Transaction... transactionsToAdd) { private void appendBlock(final Transaction... transactionsToAdd) {
appendBlock(UInt256.ONE, getHeaderForCurrentChainHead(), transactionsToAdd); appendBlock(Difficulty.ONE, getHeaderForCurrentChainHead(), transactionsToAdd);
} }
private BlockHeader getHeaderForCurrentChainHead() { private BlockHeader getHeaderForCurrentChainHead() {
@ -627,7 +628,7 @@ public class TransactionPoolTest {
} }
private Block appendBlock( private Block appendBlock(
final UInt256 difficulty, final Difficulty difficulty,
final BlockHeader parentBlock, final BlockHeader parentBlock,
final Transaction... transactionsToAdd) { final Transaction... transactionsToAdd) {
final List<Transaction> transactionList = asList(transactionsToAdd); final List<Transaction> transactionList = asList(transactionsToAdd);

@ -65,7 +65,7 @@ public class TestSetChainParamsTest {
"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
assertThat(blockHeader.getCoinbase().toString()) assertThat(blockHeader.getCoinbase().toString())
.isEqualTo("0x8888f1f195afa192cfee860698584c030f4c9db1"); .isEqualTo("0x8888f1f195afa192cfee860698584c030f4c9db1");
assertThat(blockHeader.internalGetDifficulty()).isEqualTo(UInt256.fromHexString("0x20000")); assertThat(blockHeader.getDifficulty()).isEqualTo(UInt256.fromHexString("0x20000"));
assertThat(blockHeader.getExtraData().getHexString()).isEqualTo("0x42"); assertThat(blockHeader.getExtraData().getHexString()).isEqualTo("0x42");
assertThat(blockHeader.getGasLimit()).isEqualTo(3141592); assertThat(blockHeader.getGasLimit()).isEqualTo(3141592);
assertThat(blockHeader.getGasUsed()).isEqualTo(0); assertThat(blockHeader.getGasUsed()).isEqualTo(0);

Loading…
Cancel
Save