diff --git a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/Hedera.java b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/Hedera.java index dc43bd8e544d..ba09ead52f0f 100644 --- a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/Hedera.java +++ b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/Hedera.java @@ -84,11 +84,11 @@ import com.swirlds.common.crypto.CryptographyHolder; import com.swirlds.common.platform.NodeId; import com.swirlds.platform.listeners.PlatformStatusChangeListener; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldMain; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.events.Event; @@ -370,7 +370,7 @@ public SwirldState newState() { private void onStateInitialized( @NonNull final MerkleHederaState state, @NonNull final Platform platform, - @NonNull final SwirldDualState dualState, + @NonNull final PlatformState platformState, @NonNull final InitTrigger trigger, @Nullable final SoftwareVersion previousVersion) { // Initialize the configuration from disk. We must do this BEFORE we run migration, because the various @@ -407,7 +407,7 @@ private void onStateInitialized( } //noinspection ConstantValue - assert dualState != null : "Platform should never pass a null dual state"; + assert platformState != null : "Platform should never pass a null platform state"; logger.info( "Initializing Hedera state with trigger {} and previous version {}", () -> trigger, @@ -449,11 +449,11 @@ private void onStateInitialized( // assertion will hold true. assert configProvider != null : "Config Provider *must* have been set by now!"; - // Some logging on what we found about freeze in the dual state + // Some logging on what we found about freeze in the platform state logger.info( - "Dual state includes freeze time={} and last frozen={}", - dualState.getFreezeTime(), - dualState.getLastFrozenTime()); + "Platform state includes freeze time={} and last frozen={}", + platformState.getFreezeTime(), + platformState.getLastFrozenTime()); } /** * Called by this class when we detect it is time to do migration. The {@code deserializedVersion} must not be newer @@ -720,9 +720,9 @@ private void onPreHandle(@NonNull final Event event, @NonNull final HederaState * called. */ private void onHandleConsensusRound( - @NonNull final Round round, @NonNull final SwirldDualState dualState, @NonNull final HederaState state) { + @NonNull final Round round, @NonNull final PlatformState platformState, @NonNull final HederaState state) { daggerApp.workingStateAccessor().setHederaState(state); - daggerApp.handleWorkflow().handleRound(state, dualState, round); + daggerApp.handleWorkflow().handleRound(state, platformState, round); } /*================================================================================================================== diff --git a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/HederaInjectionComponent.java b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/HederaInjectionComponent.java index 4bf5eb255ebc..5cbec646e957 100644 --- a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/HederaInjectionComponent.java +++ b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/HederaInjectionComponent.java @@ -46,8 +46,8 @@ import com.hedera.node.app.throttle.SynchronizedThrottleAccumulator; import com.hedera.node.app.throttle.ThrottleManager; import com.hedera.node.app.workflows.WorkflowsInjectionModule; -import com.hedera.node.app.workflows.handle.DualStateUpdateFacility; import com.hedera.node.app.workflows.handle.HandleWorkflow; +import com.hedera.node.app.workflows.handle.PlatformStateUpdateFacility; import com.hedera.node.app.workflows.handle.SystemFileUpdateFacility; import com.hedera.node.app.workflows.handle.record.GenesisRecordsConsensusHook; import com.hedera.node.app.workflows.prehandle.PreHandleWorkflow; @@ -118,7 +118,7 @@ public interface HederaInjectionComponent { ThrottleManager throttleManager(); - DualStateUpdateFacility dualStateUpdateFacility(); + PlatformStateUpdateFacility platformStateUpdateFacility(); GenesisRecordsConsensusHook genesisRecordsConsensusHook(); diff --git a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/HandleConsensusRoundListener.java b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/HandleConsensusRoundListener.java index 213acf251478..07f55381c966 100644 --- a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/HandleConsensusRoundListener.java +++ b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/HandleConsensusRoundListener.java @@ -16,12 +16,12 @@ package com.hedera.node.app.state; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import edu.umd.cs.findbugs.annotations.NonNull; /** Listener invoked for each consensus round that occurs. */ @FunctionalInterface public interface HandleConsensusRoundListener { - void onConsensusRound(@NonNull Round round, @NonNull SwirldDualState dualState, @NonNull HederaState state); + void onConsensusRound(@NonNull Round round, @NonNull PlatformState platformState, @NonNull HederaState state); } diff --git a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/merkle/MerkleHederaState.java b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/merkle/MerkleHederaState.java index cfbd69271962..6f3dd5052cf3 100644 --- a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/merkle/MerkleHederaState.java +++ b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/merkle/MerkleHederaState.java @@ -52,11 +52,11 @@ import com.swirlds.common.merkle.impl.PartialNaryMerkleInternal; import com.swirlds.common.utility.Labeled; import com.swirlds.merkle.map.MerkleMap; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldMain; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.events.Event; @@ -190,14 +190,14 @@ public MerkleHederaState() { @Override public void init( final Platform platform, - final SwirldDualState dualState, + final PlatformState platformState, final InitTrigger trigger, final SoftwareVersion deserializedVersion) { // At some point this method will no longer be defined on SwirldState2, because we want to move // to a model where SwirldState/SwirldState2 are simply data objects, without this lifecycle. // Instead, this method will be a callback the app registers with the platform. So for now, // we simply call the callback handler, which is implemented by the app. - this.onInit.onStateInitialized(this, platform, dualState, trigger, deserializedVersion); + this.onInit.onStateInitialized(this, platform, platformState, trigger, deserializedVersion); } /** @@ -307,10 +307,10 @@ public MerkleHederaState copy() { * {@inheritDoc} */ @Override - public void handleConsensusRound(@NonNull final Round round, @NonNull final SwirldDualState swirldDualState) { + public void handleConsensusRound(@NonNull final Round round, @NonNull final PlatformState platformState) { throwIfImmutable(); if (onHandleConsensusRound != null) { - onHandleConsensusRound.onConsensusRound(round, swirldDualState, this); + onHandleConsensusRound.onConsensusRound(round, platformState, this); } } diff --git a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/merkle/OnStateInitialized.java b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/merkle/OnStateInitialized.java index b19d65ec423a..0ca3e0fcdfe0 100644 --- a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/merkle/OnStateInitialized.java +++ b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/state/merkle/OnStateInitialized.java @@ -16,10 +16,10 @@ package com.hedera.node.app.state.merkle; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; @@ -30,7 +30,7 @@ public interface OnStateInitialized { void onStateInitialized( @NonNull MerkleHederaState state, @NonNull Platform platform, - @NonNull SwirldDualState dualState, + @NonNull PlatformState platformState, @NonNull InitTrigger trigger, @Nullable SoftwareVersion deserializedVersion); } diff --git a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/HandleWorkflow.java b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/HandleWorkflow.java index 7634cfd0f877..5ea45a02be1f 100644 --- a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/HandleWorkflow.java +++ b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/HandleWorkflow.java @@ -94,8 +94,8 @@ import com.hedera.node.config.data.HederaConfig; import com.hedera.pbj.runtime.io.buffer.Bytes; import com.swirlds.config.api.Configuration; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.events.ConsensusEvent; import com.swirlds.platform.system.transaction.ConsensusTransaction; import edu.umd.cs.findbugs.annotations.NonNull; @@ -134,7 +134,7 @@ public class HandleWorkflow { private final ChildRecordFinalizer childRecordFinalizer; private final ParentRecordFinalizer transactionFinalizer; private final SystemFileUpdateFacility systemFileUpdateFacility; - private final DualStateUpdateFacility dualStateUpdateFacility; + private final PlatformStateUpdateFacility platformStateUpdateFacility; private final SolvencyPreCheck solvencyPreCheck; private final Authorizer authorizer; private final NetworkUtilizationManager networkUtilizationManager; @@ -156,7 +156,7 @@ public HandleWorkflow( @NonNull final ChildRecordFinalizer childRecordFinalizer, @NonNull final ParentRecordFinalizer transactionFinalizer, @NonNull final SystemFileUpdateFacility systemFileUpdateFacility, - @NonNull final DualStateUpdateFacility dualStateUpdateFacility, + @NonNull final PlatformStateUpdateFacility platformStateUpdateFacility, @NonNull final SolvencyPreCheck solvencyPreCheck, @NonNull final Authorizer authorizer, @NonNull final NetworkUtilizationManager networkUtilizationManager) { @@ -176,8 +176,8 @@ public HandleWorkflow( this.transactionFinalizer = requireNonNull(transactionFinalizer, "transactionFinalizer must not be null"); this.systemFileUpdateFacility = requireNonNull(systemFileUpdateFacility, "systemFileUpdateFacility must not be null"); - this.dualStateUpdateFacility = - requireNonNull(dualStateUpdateFacility, "dualStateUpdateFacility must not be null"); + this.platformStateUpdateFacility = + requireNonNull(platformStateUpdateFacility, "platformStateUpdateFacility must not be null"); this.solvencyPreCheck = requireNonNull(solvencyPreCheck, "solvencyPreCheck must not be null"); this.authorizer = requireNonNull(authorizer, "authorizer must not be null"); this.networkUtilizationManager = @@ -191,7 +191,7 @@ public HandleWorkflow( * @param round the next {@link Round} that needs to be processed */ public void handleRound( - @NonNull final HederaState state, @NonNull final SwirldDualState dualState, @NonNull final Round round) { + @NonNull final HederaState state, @NonNull final PlatformState platformState, @NonNull final Round round) { // Keep track of whether any user transactions were handled. If so, then we will need to close the round // with the block record manager. final var userTransactionsHandled = new AtomicBoolean(false); @@ -222,7 +222,7 @@ public void handleRound( // skip system transactions if (!platformTxn.isSystem()) { userTransactionsHandled.set(true); - handlePlatformTransaction(state, dualState, event, creator, platformTxn); + handlePlatformTransaction(state, platformState, event, creator, platformTxn); } } catch (final Exception e) { logger.fatal( @@ -244,7 +244,7 @@ public void handleRound( private void handlePlatformTransaction( @NonNull final HederaState state, - @NonNull final SwirldDualState dualState, + @NonNull final PlatformState platformState, @NonNull final ConsensusEvent platformEvent, @NonNull final NodeInfo creator, @NonNull final ConsensusTransaction platformTxn) { @@ -253,13 +253,13 @@ private void handlePlatformTransaction( final Instant consensusNow = platformTxn.getConsensusTimestamp().minusNanos(1000 - 3L); // handle user transaction - handleUserTransaction(consensusNow, state, dualState, platformEvent, creator, platformTxn); + handleUserTransaction(consensusNow, state, platformState, platformEvent, creator, platformTxn); } private void handleUserTransaction( @NonNull final Instant consensusNow, @NonNull final HederaState state, - @NonNull final SwirldDualState dualState, + @NonNull final PlatformState platformState, @NonNull final ConsensusEvent platformEvent, @NonNull final NodeInfo creator, @NonNull final ConsensusTransaction platformTxn) { @@ -479,8 +479,8 @@ private void handleUserTransaction( final var fileUpdateResult = systemFileUpdateFacility.handleTxBody(stack, txBody); recordBuilder.status(fileUpdateResult); - // Notify if dual state was updated - dualStateUpdateFacility.handleTxBody(stack, dualState, txBody); + // Notify if platform state was updated + platformStateUpdateFacility.handleTxBody(stack, platformState, txBody); } catch (final HandleException e) { // In case of a ContractCall when it reverts, the gas charged should not be rolled back diff --git a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/DualStateUpdateFacility.java b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/PlatformStateUpdateFacility.java similarity index 84% rename from hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/DualStateUpdateFacility.java rename to hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/PlatformStateUpdateFacility.java index 4429f2d71121..e698606b3024 100644 --- a/hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/DualStateUpdateFacility.java +++ b/hedera-node/hedera-app/src/main/java/com/hedera/node/app/workflows/handle/PlatformStateUpdateFacility.java @@ -29,7 +29,7 @@ import com.hedera.node.app.spi.state.ReadableSingletonState; import com.hedera.node.app.spi.state.ReadableStates; import com.hedera.node.app.state.HederaState; -import com.swirlds.platform.system.DualState; +import com.swirlds.platform.state.PlatformState; import edu.umd.cs.findbugs.annotations.NonNull; import java.time.Instant; import javax.inject.Inject; @@ -41,14 +41,14 @@ * Simple facility that notifies interested parties when the freeze state is updated. */ @Singleton -public class DualStateUpdateFacility { - private static final Logger logger = LogManager.getLogger(DualStateUpdateFacility.class); +public class PlatformStateUpdateFacility { + private static final Logger logger = LogManager.getLogger(PlatformStateUpdateFacility.class); /** * Creates a new instance of this class. */ @Inject - public DualStateUpdateFacility() { + public PlatformStateUpdateFacility() { // For dagger } @@ -61,7 +61,7 @@ public DualStateUpdateFacility() { */ public void handleTxBody( @NonNull final HederaState state, - @NonNull final DualState dualState, + @NonNull final PlatformState platformState, @NonNull final TransactionBody txBody) { requireNonNull(state, "state must not be null"); requireNonNull(txBody, "txBody must not be null"); @@ -70,7 +70,7 @@ public void handleTxBody( final FreezeType freezeType = txBody.freezeOrThrow().freezeType(); if (freezeType == FREEZE_UPGRADE || freezeType == FREEZE_ONLY) { logger.info("Transaction freeze of type {} detected", freezeType); - // copy freeze state to dual state + // copy freeze state to platform state final ReadableStates states = state.createReadableStates(FreezeService.NAME); final ReadableSingletonState freezeTime = states.getSingleton(FreezeServiceImpl.FREEZE_TIME_KEY); @@ -78,12 +78,12 @@ public void handleTxBody( final Instant freezeTimeInstant = Instant.ofEpochSecond( freezeTime.get().seconds(), freezeTime.get().nanos()); logger.info("Freeze time will be {}", freezeTimeInstant); - dualState.setFreezeTime(freezeTimeInstant); + platformState.setFreezeTime(freezeTimeInstant); } else if (freezeType == FREEZE_ABORT) { logger.info("Aborting freeze"); - // copy freeze state (which is null) to dual state - // we just set dual state to null - dualState.setFreezeTime(null); + // copy freeze state (which is null) to platform state + // we just set platform state to null + platformState.setFreezeTime(null); } // else for other freeze types, do nothing } diff --git a/hedera-node/hedera-app/src/test/java/com/hedera/node/app/state/merkle/MerkleHederaStateTest.java b/hedera-node/hedera-app/src/test/java/com/hedera/node/app/state/merkle/MerkleHederaStateTest.java index 876d8ebb71b5..47af6d8bc664 100644 --- a/hedera-node/hedera-app/src/test/java/com/hedera/node/app/state/merkle/MerkleHederaStateTest.java +++ b/hedera-node/hedera-app/src/test/java/com/hedera/node/app/state/merkle/MerkleHederaStateTest.java @@ -31,8 +31,8 @@ import com.swirlds.base.state.MutabilityException; import com.swirlds.common.merkle.MerkleNode; import com.swirlds.merkle.map.MerkleMap; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.events.Event; import java.util.ArrayList; import java.util.Collections; @@ -65,7 +65,7 @@ void setUp() { hederaMerkle = new MerkleHederaState( (tree, state) -> onPreHandleCalled.set(true), (evt, meta, state) -> onHandleCalled.set(true), - (state, platform, dual, trigger, version) -> onMigrateCalled.set(true)); + (state, platform, platformState, trigger, version) -> onMigrateCalled.set(true)); } /** Looks for a merkle node with the given label */ @@ -688,7 +688,7 @@ final class ConsensusRoundTest { @DisplayName("Notifications are sent to onHandleConsensusRound when handleConsensusRound is called") void handleConsensusRoundCallback() { final var round = Mockito.mock(Round.class); - final var dualState = Mockito.mock(SwirldDualState.class); + final var platformState = Mockito.mock(PlatformState.class); final var state = new MerkleHederaState( (tree, st) -> onPreHandleCalled.set(true), (evt, meta, provider) -> { @@ -697,7 +697,7 @@ void handleConsensusRoundCallback() { }, (s, p, d, t, v) -> {}); - state.handleConsensusRound(round, dualState); + state.handleConsensusRound(round, platformState); assertThat(onHandleCalled).isTrue(); } } @@ -712,11 +712,11 @@ void originalLosesConsensusRoundCallbackAfterCopy() { // The original no longer has the listener final var round = Mockito.mock(Round.class); - final var dualState = Mockito.mock(SwirldDualState.class); - assertThrows(MutabilityException.class, () -> hederaMerkle.handleConsensusRound(round, dualState)); + final var platformState = Mockito.mock(PlatformState.class); + assertThrows(MutabilityException.class, () -> hederaMerkle.handleConsensusRound(round, platformState)); // But the copy does - copy.handleConsensusRound(round, dualState); + copy.handleConsensusRound(round, platformState); assertThat(onHandleCalled).isTrue(); } diff --git a/hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/HandleWorkflowTest.java b/hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/HandleWorkflowTest.java index d5e4c71f84cc..5b56965e28f3 100644 --- a/hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/HandleWorkflowTest.java +++ b/hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/HandleWorkflowTest.java @@ -75,8 +75,8 @@ import com.hedera.node.config.VersionedConfigImpl; import com.hedera.node.config.testfixtures.HederaTestConfigBuilder; import com.hedera.pbj.runtime.io.buffer.Bytes; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.events.ConsensusEvent; import com.swirlds.platform.system.transaction.ConsensusTransaction; import com.swirlds.platform.system.transaction.SwirldTransaction; @@ -196,7 +196,7 @@ private static PreHandleResult createPreHandleResult(@NonNull Status status, @No private NetworkUtilizationManager networkUtilizationManager; @Mock - private DualStateUpdateFacility dualStateUpdateFacility; + private PlatformStateUpdateFacility platformStateUpdateFacility; @Mock(strictness = LENIENT) private SolvencyPreCheck solvencyPreCheck; @@ -205,7 +205,7 @@ private static PreHandleResult createPreHandleResult(@NonNull Status status, @No private Authorizer authorizer; @Mock - private SwirldDualState dualState; + private PlatformState platformState; private HandleWorkflow workflow; @@ -276,7 +276,7 @@ void setup() throws PreCheckException { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager); @@ -301,7 +301,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -322,7 +322,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -343,7 +343,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -364,7 +364,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -385,7 +385,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -406,7 +406,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -427,7 +427,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -448,7 +448,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -469,7 +469,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -490,7 +490,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -511,7 +511,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -532,7 +532,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -553,7 +553,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, null, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -574,7 +574,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, null, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, networkUtilizationManager)) @@ -616,7 +616,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, null, authorizer, networkUtilizationManager)) @@ -637,7 +637,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, null, networkUtilizationManager)) @@ -658,7 +658,7 @@ void testContructorWithInvalidArguments() { childRecordFinalizer, finalizer, systemFileUpdateFacility, - dualStateUpdateFacility, + platformStateUpdateFacility, solvencyPreCheck, authorizer, null)) @@ -672,7 +672,7 @@ void testPlatformTxnIsSkipped() { when(platformTxn.isSystem()).thenReturn(true); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then assertThat(accountsState.isModified()).isFalse(); @@ -689,7 +689,7 @@ void testHappyPath() { .willAnswer(invocation -> invocation.getArgument(4)); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -697,7 +697,7 @@ void testHappyPath() { assertThat(alice).isEqualTo(ALICE.account().accountId()); // TODO: Check that record was created verify(systemFileUpdateFacility).handleTxBody(any(), any()); - verify(dualStateUpdateFacility).handleTxBody(any(), any(), any()); + verify(platformStateUpdateFacility).handleTxBody(any(), any(), any()); } @Nested @@ -717,7 +717,7 @@ void testPreHandleNotExecuted() { when(platformTxn.getMetadata()).thenReturn(null); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -731,7 +731,7 @@ void testPreHandleFailure() { when(platformTxn.getMetadata()).thenReturn(PRE_HANDLE_FAILURE_RESULT); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -747,7 +747,7 @@ void testUnknownFailure() { when(platformTxn.getMetadata()).thenReturn(unknownFailure); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -774,7 +774,7 @@ void testConfigurationChanged() { when(platformTxn.getMetadata()).thenReturn(preHandleResult); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(preHandleWorkflow).preHandleTransaction(any(), any(), any(), eq(platformTxn), eq(preHandleResult)); @@ -787,7 +787,7 @@ void testPreHandleSuccess() { when(platformTxn.getMetadata()).thenReturn(null); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -808,7 +808,7 @@ void testPreHandleCausesDueDilligenceError() { .thenReturn(DUE_DILIGENCE_RESULT); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -825,7 +825,7 @@ void testPreHandleCausesPreHandleFailure() { .thenReturn(DUE_DILIGENCE_RESULT); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -841,7 +841,7 @@ void testPreHandleCausesUnknownFailure() { .thenReturn(PreHandleResult.unknownFailure()); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -857,7 +857,7 @@ void testPreHandleWithDueDiligenceFailure() { // given when(platformTxn.getMetadata()).thenReturn(DUE_DILIGENCE_RESULT); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -899,7 +899,7 @@ void testRequiredExistingKeyWithFailingSignature() throws PreCheckException { .dispatchPreHandle(any()); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(dispatcher, never()).dispatchHandle(any()); @@ -919,7 +919,7 @@ void testRequiredNewKeyWithFailingSignature() throws PreCheckException { .dispatchPreHandle(any()); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(dispatcher, never()).dispatchHandle(any()); @@ -960,7 +960,7 @@ void testOptionalExistingKeyWithPassingSignature() throws PreCheckException { .dispatchPreHandle(any()); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then final var argCapture = ArgumentCaptor.forClass(HandleContext.class); @@ -1004,7 +1004,7 @@ void testComplexCase() { .willAnswer(invocation -> invocation.getArgument(4)); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then final var argCapture = ArgumentCaptor.forClass(HandleContext.class); @@ -1042,7 +1042,7 @@ void testDuplicateFromOtherNode() { .thenReturn(DuplicateCheckResult.OTHER_NODE); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1062,7 +1062,7 @@ void testDuplicateFromSameNode() { .thenReturn(DuplicateCheckResult.SAME_NODE); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1083,7 +1083,7 @@ void testExpiredTransactionFails(final ResponseCodeEnum responseCode) throws Pre .checkTimeBox(OK_RESULT.txInfo().txBody(), TX_CONSENSUS_NOW); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1113,7 +1113,7 @@ void testInvalidPayerAccountFails(final ResponseCodeEnum responseCode) throws Pr .getPayerAccount(any(), eq(ALICE.accountID())); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1142,7 +1142,7 @@ void testInsolventPayerAccountFails(final ResponseCodeEnum responseCode) throws .checkSolvency(eq(OK_RESULT.txInfo()), any(), eq(DEFAULT_FEES), eq(FALSE)); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1163,7 +1163,7 @@ void testNonAuthorizedAccountFails() { .thenReturn(false); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1188,7 +1188,7 @@ void testNonAuthorizedAccountFailsForPrivilegedTxn() { .thenReturn(SystemPrivilege.UNAUTHORIZED); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1213,7 +1213,7 @@ void testImpermissibleTransactionFails() { .thenReturn(SystemPrivilege.IMPERMISSIBLE); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1239,7 +1239,7 @@ void testAuthorizedAccountFailsForPrivilegedTxn(final SystemPrivilege privilege) .thenReturn(privilege); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1258,7 +1258,7 @@ void testHandleException() { doThrow(new HandleException(ResponseCodeEnum.INVALID_SIGNATURE)) .when(dispatcher) .dispatchHandle(any()); - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1271,7 +1271,7 @@ void testHandleException() { void testUnknownFailure() { // when doThrow(new ArrayIndexOutOfBoundsException()).when(dispatcher).dispatchHandle(any()); - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1293,7 +1293,7 @@ void testSimpleRun() { given(preHandleWorkflow.preHandleTransaction(any(), any(), any(), any(), any())) .willAnswer(invocation -> invocation.getArgument(4)); // when - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); // then verify(blockRecordManager).advanceConsensusClock(notNull(), notNull()); @@ -1305,7 +1305,7 @@ void testSimpleRun() { @Test void testConsensusTimeHooksCalled() { - workflow.handleRound(state, dualState, round); + workflow.handleRound(state, platformState, round); verify(genesisRecordsTimeHook).process(notNull()); verify(stakingPeriodTimeHook).process(notNull(), notNull()); } diff --git a/hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/DualStateUpdateFacilityTest.java b/hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/PlatformStateUpdateFacilityTest.java similarity index 81% rename from hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/DualStateUpdateFacilityTest.java rename to hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/PlatformStateUpdateFacilityTest.java index a33743d7cf86..b1db1444f285 100644 --- a/hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/DualStateUpdateFacilityTest.java +++ b/hedera-node/hedera-app/src/test/java/com/hedera/node/app/workflows/handle/PlatformStateUpdateFacilityTest.java @@ -34,7 +34,7 @@ import com.hedera.node.app.spi.fixtures.TransactionFactory; import com.hedera.node.app.spi.state.WritableSingletonStateBase; import com.hedera.node.app.spi.state.WritableStates; -import com.swirlds.platform.system.SwirldDualState; +import com.swirlds.platform.state.PlatformState; import java.time.Instant; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -47,14 +47,14 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -class DualStateUpdateFacilityTest implements TransactionFactory { +class PlatformStateUpdateFacilityTest implements TransactionFactory { private FakeHederaState state; - private DualStateUpdateFacility subject; + private PlatformStateUpdateFacility subject; private AtomicReference freezeTimeBackingStore; @Mock(strictness = Strictness.LENIENT) - private SwirldDualState dualState; + private PlatformState platformState; @Mock(strictness = LENIENT) protected WritableStates writableStates; @@ -68,11 +68,11 @@ void setUp() { state = new FakeHederaState().addService(FreezeService.NAME, Map.of(FREEZE_TIME_KEY, freezeTimeBackingStore)); - doAnswer(answer -> when(dualState.getFreezeTime()).thenReturn(answer.getArgument(0))) - .when(dualState) + doAnswer(answer -> when(platformState.getFreezeTime()).thenReturn(answer.getArgument(0))) + .when(platformState) .setFreezeTime(any(Instant.class)); - subject = new DualStateUpdateFacility(); + subject = new PlatformStateUpdateFacility(); } @SuppressWarnings("ConstantConditions") @@ -82,10 +82,11 @@ void testMethodsWithInvalidArguments() { final var txBody = simpleCryptoTransfer().body(); // then - assertThatThrownBy(() -> subject.handleTxBody(null, dualState, txBody)) + assertThatThrownBy(() -> subject.handleTxBody(null, platformState, txBody)) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> subject.handleTxBody(state, null, txBody)).isInstanceOf(NullPointerException.class); - assertThatThrownBy(() -> subject.handleTxBody(state, dualState, null)).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> subject.handleTxBody(state, platformState, null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -96,7 +97,7 @@ void testCryptoTransferShouldBeNoOp() { .build(); // then - Assertions.assertThatCode(() -> subject.handleTxBody(state, dualState, txBody)) + Assertions.assertThatCode(() -> subject.handleTxBody(state, platformState, txBody)) .doesNotThrowAnyException(); } @@ -109,10 +110,10 @@ void testFreezeUpgrade() { .freeze(FreezeTransactionBody.newBuilder().freezeType(FREEZE_UPGRADE)); // when - subject.handleTxBody(state, dualState, txBody.build()); + subject.handleTxBody(state, platformState, txBody.build()); // then - assertEquals(freezeTime.seconds(), dualState.getFreezeTime().getEpochSecond()); - assertEquals(freezeTime.nanos(), dualState.getFreezeTime().getNano()); + assertEquals(freezeTime.seconds(), platformState.getFreezeTime().getEpochSecond()); + assertEquals(freezeTime.nanos(), platformState.getFreezeTime().getNano()); } } diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/ServicesApp.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/ServicesApp.java index 932e524ed479..d5e04ab6676a 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/ServicesApp.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/ServicesApp.java @@ -45,7 +45,7 @@ import com.hedera.node.app.service.mono.records.RecordsModule; import com.hedera.node.app.service.mono.sigs.EventExpansion; import com.hedera.node.app.service.mono.sigs.SigsModule; -import com.hedera.node.app.service.mono.state.DualStateAccessor; +import com.hedera.node.app.service.mono.state.PlatformStateAccessor; import com.hedera.node.app.service.mono.state.StateModule; import com.hedera.node.app.service.mono.state.expiry.ExpiryModule; import com.hedera.node.app.service.mono.state.exports.AccountsExporter; @@ -135,7 +135,7 @@ public interface ServicesApp { ServicesInitFlow initializationFlow(); - DualStateAccessor dualStateAccessor(); + PlatformStateAccessor platformStateAccessor(); VirtualMapFactory virtualMapFactory(); diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/ServicesState.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/ServicesState.java index 84fc694be791..eb7f0484bf1c 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/ServicesState.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/ServicesState.java @@ -85,12 +85,11 @@ import com.swirlds.merkle.map.MerkleMap; import com.swirlds.merkledb.MerkleDb; import com.swirlds.platform.gui.SwirldsGui; -import com.swirlds.platform.state.DualStateImpl; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.address.AddressBook; import com.swirlds.platform.system.events.Event; @@ -239,14 +238,14 @@ public MerkleNode migrate(final int version) { @Override public void init( final Platform platform, - final SwirldDualState dualState, + final PlatformState platformState, final InitTrigger trigger, final SoftwareVersion deserializedVersion) { // first store a reference to the platform this.platform = platform; if (trigger == GENESIS) { - genesisInit(platform, dualState); + genesisInit(platform, platformState); } else { if (deserializedVersion == null) { throw new IllegalStateException( @@ -266,7 +265,7 @@ public void init( // Note this returns the app in case we need to do something with it after making // final changes to state (e.g. after migrating something from memory to disk) - deserializedInit(platform, dualState, trigger, deserializedVersion); + deserializedInit(platform, platformState, trigger, deserializedVersion); final var isUpgrade = SEMANTIC_VERSIONS.deployedSoftwareVersion().isNonConfigUpgrade(deserializedVersion); if (isUpgrade) { migrateFrom(deserializedVersion); @@ -292,13 +291,13 @@ public void init( } @Override - public void handleConsensusRound(final Round round, final SwirldDualState dualState) { + public void handleConsensusRound(final Round round, final PlatformState platformState) { throwIfImmutable(); final var app = metadata.app(); app.mapWarmer().warmCache(round); - app.dualStateAccessor().setDualState(dualState); + app.platformStateAccessor().setPlatformState(platformState); app.logic().incorporateConsensus(round); } @@ -327,7 +326,7 @@ public AddressBook updateWeight(@NonNull AddressBook configAddressBook, @NonNull private ServicesApp deserializedInit( final Platform platform, - final SwirldDualState dualState, + final PlatformState platformState, final InitTrigger trigger, @NonNull final SoftwareVersion deserializedVersion) { log.info("Init called on Services node {} WITH Merkle saved state", platform.getSelfId()); @@ -336,10 +335,10 @@ private ServicesApp deserializedInit( enableVirtualAccounts = bootstrapProps.getBooleanProperty(PropertyNames.ACCOUNTS_STORE_ON_DISK); enableVirtualTokenRels = bootstrapProps.getBooleanProperty(PropertyNames.TOKENS_STORE_RELS_ON_DISK); enabledVirtualNft = bootstrapProps.getBooleanProperty(PropertyNames.TOKENS_NFTS_USE_VIRTUAL_MERKLE); - return internalInit(platform, bootstrapProps, dualState, trigger, deserializedVersion); + return internalInit(platform, bootstrapProps, platformState, trigger, deserializedVersion); } - private void genesisInit(final Platform platform, final SwirldDualState dualState) { + private void genesisInit(final Platform platform, final PlatformState platformState) { log.info("Init called on Services node {} WITHOUT Merkle saved state", platform.getSelfId()); // Create the top-level children in the Merkle tree @@ -350,14 +349,14 @@ private void genesisInit(final Platform platform, final SwirldDualState dualStat enabledVirtualNft = bootstrapProps.getBooleanProperty(PropertyNames.TOKENS_NFTS_USE_VIRTUAL_MERKLE); consolidateRecordStorage = bootstrapProps.getBooleanProperty(PropertyNames.RECORDS_USE_CONSOLIDATED_FCQ); createGenesisChildren(platform.getAddressBook(), seqStart, bootstrapProps); - internalInit(platform, bootstrapProps, dualState, GENESIS, null); + internalInit(platform, bootstrapProps, platformState, GENESIS, null); networkCtx().markPostUpgradeScanStatus(); } private ServicesApp internalInit( final Platform platform, final BootstrapProperties bootstrapProps, - SwirldDualState dualState, + PlatformState platformState, final InitTrigger trigger, @Nullable final SoftwareVersion deserializedVersion) { this.platform = platform; @@ -385,14 +384,15 @@ private ServicesApp internalInit( app.maybeNewRecoveredStateListener().ifPresent(listener -> platform.getNotificationEngine() .register(NewRecoveredStateListener.class, listener)); - if (dualState == null) { - dualState = new DualStateImpl(); + if (platformState == null) { + log.error("Platform state is null, this is highly unusual."); + platformState = new PlatformState(); } - app.dualStateAccessor().setDualState(dualState); + app.platformStateAccessor().setPlatformState(platformState); log.info( - "Dual state includes freeze time={} and last frozen={}", - dualState.getFreezeTime(), - dualState.getLastFrozenTime()); + "Platform state includes freeze time={} and last frozen={}", + platformState.getFreezeTime(), + platformState.getLastFrozenTime()); final var deployedVersion = SEMANTIC_VERSIONS.deployedSoftwareVersion(); if (deployedVersion.isBefore(deserializedVersion)) { @@ -489,7 +489,7 @@ public void logSummary() { if (metadata != null) { final var app = metadata.app(); app.hashLogger().logHashesFor(this); - ctxSummary = networkCtx().summarizedWith(app.dualStateAccessor()); + ctxSummary = networkCtx().summarizedWith(app.platformStateAccessor()); } else { ctxSummary = networkCtx().summarized(); } diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/context/annotations/StaticAccountMemo.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/context/annotations/StaticAccountMemo.java index d0a52d3d80ff..890705466a11 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/context/annotations/StaticAccountMemo.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/context/annotations/StaticAccountMemo.java @@ -19,10 +19,10 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.hedera.node.app.service.mono.ServicesState; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; @@ -30,7 +30,7 @@ /** * Distinguishes a bound {@code String} instance that represents the address book memo of the node - * during {@link ServicesState#init(Platform, SwirldDualState, InitTrigger, SoftwareVersion)}. The + * during {@link ServicesState#init(Platform, PlatformState, InitTrigger, SoftwareVersion)}. The * "static" qualifier is meant to emphasize the current system does not allow for the possibility of * the node's account changing dynamically (i.e., without a network restart). */ diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/grpc/marshalling/ImpliedTransfersMeta.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/grpc/marshalling/ImpliedTransfersMeta.java index 84d0c1a0e120..fe59b7ee28f7 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/grpc/marshalling/ImpliedTransfersMeta.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/grpc/marshalling/ImpliedTransfersMeta.java @@ -25,7 +25,6 @@ import com.hedera.node.app.service.mono.utils.EntityNum; import com.hederahashgraph.api.proto.java.ResponseCodeEnum; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.events.Event; import java.util.List; import java.util.Map; @@ -39,7 +38,7 @@ * *

Note that we need to remember these two parameters in order to safely reuse this validation * across "span" between the {@link ServicesState#preHandle(Event)} and {@link - * ServicesState#handleConsensusRound(Round, SwirldDualState)} callbacks. + * ServicesState#handleConsensusRound(Round, PlatformState)} callbacks. * *

This is because either parameter could change due to an update of file 0.0.121 between * the two callbacks. So we have to double-check that neither did change before reusing the diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/sigs/HederaToPlatformSigOps.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/sigs/HederaToPlatformSigOps.java index aa2b3a7c0646..e7892792cb98 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/sigs/HederaToPlatformSigOps.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/sigs/HederaToPlatformSigOps.java @@ -26,8 +26,8 @@ import com.hederahashgraph.api.proto.java.ResponseCodeEnum; import com.hederahashgraph.api.proto.java.Transaction; import com.swirlds.common.crypto.Signature; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; /** * Provides an "expand" operation that acts in-place on the {@link @@ -43,7 +43,7 @@ * have active signatures for the wrapped gRPC txn to be valid; and creates the cryptographic * signatures at the bases of the signing hierarchies for these keys. This implicitly requests the * Platform to verify these cryptographic signatures, by setting them in the sigs list of the - * platform txn, before {@link ServicesState#handleConsensusRound(Round, SwirldDualState)} is + * platform txn, before {@link ServicesState#handleConsensusRound(Round, PlatformState)} is * called with {@code isConsensus=true}. */ public final class HederaToPlatformSigOps { diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/DualStateAccessor.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/PlatformStateAccessor.java similarity index 69% rename from hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/DualStateAccessor.java rename to hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/PlatformStateAccessor.java index fdac2d682b94..91050b9efc78 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/DualStateAccessor.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/PlatformStateAccessor.java @@ -16,24 +16,24 @@ package com.hedera.node.app.service.mono.state; -import com.swirlds.platform.system.SwirldDualState; +import com.swirlds.platform.state.PlatformState; import javax.inject.Inject; import javax.inject.Singleton; @Singleton -public class DualStateAccessor { - private SwirldDualState dualState = null; +public class PlatformStateAccessor { + private PlatformState platformState = null; @Inject - public DualStateAccessor() { + public PlatformStateAccessor() { // Default constructor } - public SwirldDualState getDualState() { - return dualState; + public PlatformState getPlatformState() { + return platformState; } - public void setDualState(SwirldDualState dualState) { - this.dualState = dualState; + public void setPlatformState(PlatformState platformState) { + this.platformState = platformState; } } diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/logic/BlockManager.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/logic/BlockManager.java index 85c81ae25531..92c41834c651 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/logic/BlockManager.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/logic/BlockManager.java @@ -24,7 +24,7 @@ import com.hedera.node.app.service.evm.contracts.execution.HederaBlockValues; import com.hedera.node.app.service.mono.context.properties.BootstrapProperties; -import com.hedera.node.app.service.mono.state.DualStateAccessor; +import com.hedera.node.app.service.mono.state.PlatformStateAccessor; import com.hedera.node.app.service.mono.state.merkle.MerkleNetworkContext; import com.hedera.node.app.service.mono.stream.RecordsRunningHashLeaf; import com.swirlds.common.crypto.RunningHash; @@ -51,7 +51,7 @@ public class BlockManager { private final long blockPeriodMs; private final boolean logEveryTransaction; - private final DualStateAccessor dualStateAccessor; + private final PlatformStateAccessor platformStateAccessor; private final Supplier networkCtx; private final Supplier runningHashLeaf; @@ -68,13 +68,13 @@ public BlockManager( final BootstrapProperties bootstrapProperties, final Supplier networkCtx, final Supplier runningHashLeaf, - final DualStateAccessor dualStateAccessor) { + final PlatformStateAccessor platformStateAccessor) { this.networkCtx = networkCtx; this.runningHashLeaf = runningHashLeaf; this.blockPeriodMs = bootstrapProperties.getLongProperty(HEDERA_RECORD_STREAM_LOG_PERIOD) * SECONDS_TO_MILLISECONDS; this.logEveryTransaction = bootstrapProperties.getBooleanProperty(HEDERA_RECORD_STREAM_LOG_EVERY_TRANSACTION); - this.dualStateAccessor = dualStateAccessor; + this.platformStateAccessor = platformStateAccessor; } /** Clears all provisional block metadata for the current transaction. */ @@ -193,11 +193,11 @@ private void computeProvisionalBlockMeta(final Instant now) { private boolean willCreateNewBlock(@NonNull final Instant timestamp) { final var curNetworkCtx = networkCtx.get(); final var firstBlockTime = curNetworkCtx.firstConsTimeOfCurrentBlock(); - final var dualState = dualStateAccessor.getDualState(); - final var isFirstTransactionAfterFreezeRestart = - dualState.getFreezeTime() != null && dualState.getFreezeTime().equals(dualState.getLastFrozenTime()); + final var platformState = platformStateAccessor.getPlatformState(); + final var isFirstTransactionAfterFreezeRestart = platformState.getFreezeTime() != null + && platformState.getFreezeTime().equals(platformState.getLastFrozenTime()); if (isFirstTransactionAfterFreezeRestart) { - dualState.setFreezeTime(null); + platformState.setFreezeTime(null); } return firstBlockTime == null || isFirstTransactionAfterFreezeRestart diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/merkle/MerkleNetworkContext.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/merkle/MerkleNetworkContext.java index e901fc53d917..81190223200e 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/merkle/MerkleNetworkContext.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/state/merkle/MerkleNetworkContext.java @@ -31,7 +31,7 @@ import com.hedera.node.app.hapi.utils.throttles.DeterministicThrottle; import com.hedera.node.app.hapi.utils.throttles.GasLimitDeterministicThrottle; import com.hedera.node.app.service.mono.fees.congestion.MultiplierSources; -import com.hedera.node.app.service.mono.state.DualStateAccessor; +import com.hedera.node.app.service.mono.state.PlatformStateAccessor; import com.hedera.node.app.service.mono.state.merkle.internals.BytesElement; import com.hedera.node.app.service.mono.state.submerkle.ExchangeRates; import com.hedera.node.app.service.mono.state.submerkle.RichInstant; @@ -522,12 +522,14 @@ public String summarized() { return summarizedWith(null); } - public String summarizedWith(final DualStateAccessor dualStateAccessor) { - final var isDualStateAvailable = dualStateAccessor != null && dualStateAccessor.getDualState() != null; - final var freezeTime = - isDualStateAvailable ? dualStateAccessor.getDualState().getFreezeTime() : null; + public String summarizedWith(final PlatformStateAccessor platformStateAccessor) { + final var isPlatformStateAvailable = + platformStateAccessor != null && platformStateAccessor.getPlatformState() != null; + final var freezeTime = isPlatformStateAvailable + ? platformStateAccessor.getPlatformState().getFreezeTime() + : null; final var pendingUpdateDesc = currentPendingUpdateDesc(); - final var pendingMaintenanceDesc = freezeTimeDesc(freezeTime, isDualStateAvailable) + pendingUpdateDesc; + final var pendingMaintenanceDesc = freezeTimeDesc(freezeTime, isPlatformStateAvailable) + pendingUpdateDesc; return "The network context (state version " + (stateVersion == UNRECORDED_STATE_VERSION ? NOT_AVAILABLE : stateVersion) @@ -665,10 +667,10 @@ private String currentPendingUpdateDesc() { + CommonUtils.hex(preparedUpdateFileHash).substring(0, 8); } - private String freezeTimeDesc(@Nullable final Instant freezeTime, final boolean isDualStateAvailable) { + private String freezeTimeDesc(@Nullable final Instant freezeTime, final boolean isPlatformStateAvailable) { final var nmtDescSkip = LINE_WRAP; if (freezeTime == null) { - return (isDualStateAvailable ? NOT_EXTANT : NOT_AVAILABLE) + nmtDescSkip; + return (isPlatformStateAvailable ? NOT_EXTANT : NOT_AVAILABLE) + nmtDescSkip; } return freezeTime + nmtDescSkip; } diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/network/NetworkLogicModule.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/network/NetworkLogicModule.java index f5f5a4e0b98a..7fc73c093a16 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/network/NetworkLogicModule.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/network/NetworkLogicModule.java @@ -20,10 +20,10 @@ import static com.hederahashgraph.api.proto.java.HederaFunctionality.UncheckedSubmit; import com.hedera.node.app.service.mono.fees.annotations.FunctionKey; -import com.hedera.node.app.service.mono.state.DualStateAccessor; +import com.hedera.node.app.service.mono.state.PlatformStateAccessor; import com.hedera.node.app.service.mono.txns.TransitionLogic; import com.hedera.node.app.service.mono.utils.UnzipUtility; -import com.swirlds.platform.system.SwirldDualState; +import com.swirlds.platform.state.PlatformState; import dagger.Module; import dagger.Provides; import dagger.multibindings.IntoMap; @@ -41,8 +41,8 @@ public static UpgradeActions.UnzipAction provideUnzipAction() { @Provides @Singleton - public static Supplier provideDualState(DualStateAccessor dualStateAccessor) { - return dualStateAccessor::getDualState; + public static Supplier providePlatformState(PlatformStateAccessor platformStateAccessor) { + return platformStateAccessor::getPlatformState; } @Provides diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/network/UpgradeActions.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/network/UpgradeActions.java index 60d1e3ca5de6..02b44bf62246 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/network/UpgradeActions.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/network/UpgradeActions.java @@ -23,7 +23,7 @@ import com.hedera.node.app.service.mono.context.properties.GlobalDynamicProperties; import com.hedera.node.app.service.mono.state.merkle.MerkleNetworkContext; import com.hedera.node.app.service.mono.state.merkle.MerkleSpecialFiles; -import com.swirlds.platform.system.SwirldDualState; +import com.swirlds.platform.state.PlatformState; import edu.umd.cs.findbugs.annotations.Nullable; import java.io.File; import java.io.IOException; @@ -67,7 +67,7 @@ public interface UnzipAction { private final UnzipAction unzipAction; private final GlobalDynamicProperties dynamicProperties; - private final Supplier dualState; + private final Supplier platformState; private final Supplier specialFiles; private final Supplier networkCtx; @@ -75,10 +75,10 @@ public interface UnzipAction { public UpgradeActions( final UnzipAction unzipAction, final GlobalDynamicProperties dynamicProperties, - final Supplier dualState, + final Supplier platformState, final Supplier specialFiles, final Supplier networkCtx) { - this.dualState = dualState; + this.platformState = platformState; this.networkCtx = networkCtx; this.unzipAction = unzipAction; this.specialFiles = specialFiles; @@ -100,18 +100,18 @@ public CompletableFuture extractSoftwareUpgrade(final byte[] archiveData) } public void scheduleFreezeOnlyAt(final Instant freezeTime) { - withNonNullDualState("schedule freeze", ds -> ds.setFreezeTime(freezeTime)); + withNonNullPlatformState("schedule freeze", ds -> ds.setFreezeTime(freezeTime)); } public void scheduleFreezeUpgradeAt(final Instant freezeTime) { - withNonNullDualState("schedule freeze", ds -> { + withNonNullPlatformState("schedule freeze", ds -> { ds.setFreezeTime(freezeTime); writeSecondMarker(FREEZE_SCHEDULED_MARKER, freezeTime); }); } public void abortScheduledFreeze() { - withNonNullDualState("abort freeze", ds -> { + withNonNullPlatformState("abort freeze", ds -> { ds.setFreezeTime(null); writeCheckMarker(FREEZE_ABORTED_MARKER); }); @@ -119,7 +119,7 @@ public void abortScheduledFreeze() { public boolean isFreezeScheduled() { final var ans = new AtomicBoolean(); - withNonNullDualState("check freeze schedule", ds -> { + withNonNullPlatformState("check freeze schedule", ds -> { final var freezeTime = ds.getFreezeTime(); ans.set(freezeTime != null && !freezeTime.equals(ds.getLastFrozenTime())); }); @@ -154,7 +154,7 @@ private CompletableFuture extractNow( private void catchUpOnMissedFreezeScheduling() { final var isUpgradePrepared = networkCtx.get().hasPreparedUpgrade(); if (isFreezeScheduled() && isUpgradePrepared) { - writeMarker(FREEZE_SCHEDULED_MARKER, dualState.get().getFreezeTime()); + writeMarker(FREEZE_SCHEDULED_MARKER, platformState.get().getFreezeTime()); } /* If we missed a FREEZE_ABORT, we are at risk of having a problem down the road. But writing a "defensive" freeze_aborted.mf is itself too risky, as it will keep @@ -183,10 +183,10 @@ private void catchUpOnMissedUpgradePrep() { extractSoftwareUpgrade(archiveData).join(); } - private void withNonNullDualState(final String actionDesc, final Consumer action) { - final var curDualState = dualState.get(); - Objects.requireNonNull(curDualState, "Cannot " + actionDesc + " without access to the dual state"); - action.accept(curDualState); + private void withNonNullPlatformState(final String actionDesc, final Consumer action) { + final var curPlatformState = platformState.get(); + Objects.requireNonNull(curPlatformState, "Cannot " + actionDesc + " without access to the platform state"); + action.accept(curPlatformState); } private void writeCheckMarker(final String file) { diff --git a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/span/ExpandHandleSpan.java b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/span/ExpandHandleSpan.java index 7951c546b790..ef5d00047db6 100644 --- a/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/span/ExpandHandleSpan.java +++ b/hedera-node/hedera-mono-service/src/main/java/com/hedera/node/app/service/mono/txns/span/ExpandHandleSpan.java @@ -22,15 +22,15 @@ import com.hedera.node.app.service.mono.utils.accessors.AccessorFactory; import com.hedera.node.app.service.mono.utils.accessors.PlatformTxnAccessor; import com.hedera.node.app.service.mono.utils.accessors.SwirldsTxnAccessor; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.events.Event; import com.swirlds.platform.system.transaction.Transaction; /** * Encapsulates a "span" that tracks our contact with a given {@link Transaction} between the {@link * EventExpansion#expandAllSigs(Event, ServicesState)} and {@link - * ServicesState#handleConsensusRound(Round, SwirldDualState)} platform callbacks. + * ServicesState#handleConsensusRound(Round, PlatformState)} platform callbacks. * *

At first this span only tracks the {@link PlatformTxnAccessor} parsed from the transaction * contents in an expiring cache. Since the parsing is a pure function of the contents, this is a diff --git a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/ServicesAppTest.java b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/ServicesAppTest.java index 544e20b21816..d4ad5bcbaa8d 100644 --- a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/ServicesAppTest.java +++ b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/ServicesAppTest.java @@ -41,7 +41,7 @@ import com.hedera.node.app.service.mono.ledger.accounts.staking.StakeStartupHelper; import com.hedera.node.app.service.mono.ledger.backing.BackingAccounts; import com.hedera.node.app.service.mono.sigs.EventExpansion; -import com.hedera.node.app.service.mono.state.DualStateAccessor; +import com.hedera.node.app.service.mono.state.PlatformStateAccessor; import com.hedera.node.app.service.mono.state.exports.ExportingRecoveredStateListener; import com.hedera.node.app.service.mono.state.exports.ServicesSignedStateListener; import com.hedera.node.app.service.mono.state.exports.SignedStateBalancesExporter; @@ -157,7 +157,7 @@ void objectGraphRootsAreAvailable() { assertThat(subject.logic(), instanceOf(StandardProcessLogic.class)); assertThat(subject.hashLogger(), instanceOf(HashLogger.class)); assertThat(subject.workingState(), instanceOf(MutableStateChildren.class)); - assertThat(subject.dualStateAccessor(), instanceOf(DualStateAccessor.class)); + assertThat(subject.platformStateAccessor(), instanceOf(PlatformStateAccessor.class)); assertThat(subject.initializationFlow(), instanceOf(ServicesInitFlow.class)); assertThat(subject.nodeLocalProperties(), instanceOf(NodeLocalProperties.class)); assertThat(subject.recordStreamManager(), instanceOf(RecordStreamManager.class)); diff --git a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/ServicesStateTest.java b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/ServicesStateTest.java index 77e637c10d56..df5eca287ecd 100644 --- a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/ServicesStateTest.java +++ b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/ServicesStateTest.java @@ -48,7 +48,7 @@ import com.hedera.node.app.service.mono.context.properties.PropertyNames; import com.hedera.node.app.service.mono.ledger.accounts.staking.StakeStartupHelper; import com.hedera.node.app.service.mono.sigs.EventExpansion; -import com.hedera.node.app.service.mono.state.DualStateAccessor; +import com.hedera.node.app.service.mono.state.PlatformStateAccessor; import com.hedera.node.app.service.mono.state.exports.ExportingRecoveredStateListener; import com.hedera.node.app.service.mono.state.forensics.HashLogger; import com.hedera.node.app.service.mono.state.initialization.SystemAccountsCreator; @@ -93,14 +93,13 @@ import com.swirlds.common.platform.NodeId; import com.swirlds.fchashmap.FCHashMap; import com.swirlds.merkle.map.MerkleMap; -import com.swirlds.platform.state.DualStateImpl; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.signed.ReservedSignedState; import com.swirlds.platform.state.signed.SignedStateFileReader; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.address.Address; import com.swirlds.platform.system.address.AddressBook; import com.swirlds.platform.system.events.Event; @@ -172,7 +171,7 @@ class ServicesStateTest extends ResponsibleVMapUser { private EventExpansion eventExpansion; @Mock - private SwirldDualState dualState; + private PlatformState platformState; @Mock private StateMetadata metadata; @@ -187,7 +186,7 @@ class ServicesStateTest extends ResponsibleVMapUser { private MutableStateChildren workingState; @Mock - private DualStateAccessor dualStateAccessor; + private PlatformStateAccessor platformStateAccessor; @Mock private ServicesInitFlow initFlow; @@ -300,10 +299,10 @@ void logsSummaryAsExpectedWithAppAvailable() { given(metadata.app()).willReturn(app); given(app.hashLogger()).willReturn(hashLogger); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(networkContext.getStateVersion()).willReturn(StateVersions.CURRENT_VERSION); given(networkContext.consensusTimeOfLastHandledTxn()).willReturn(consTime); - given(networkContext.summarizedWith(dualStateAccessor)).willReturn("IMAGINE"); + given(networkContext.summarizedWith(platformStateAccessor)).willReturn("IMAGINE"); // when: subject.logSummary(); @@ -372,7 +371,7 @@ void preHandleUsesEventExpansion() { void handleThrowsIfImmutable() { tracked(subject.copy()); - assertThrows(MutabilityException.class, () -> subject.handleConsensusRound(round, dualState)); + assertThrows(MutabilityException.class, () -> subject.handleConsensusRound(round, platformState)); } @Test @@ -383,11 +382,11 @@ void handlesRoundAsExpected() { final var mapWarmer = mock(EntityMapWarmer.class); given(app.mapWarmer()).willReturn(mapWarmer); given(app.logic()).willReturn(logic); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); - subject.handleConsensusRound(round, dualState); + subject.handleConsensusRound(round, platformState); verify(mapWarmer).warmCache(round); - verify(dualStateAccessor).setDualState(dualState); + verify(platformStateAccessor).setPlatformState(platformState); verify(logic).incorporateConsensus(round); } @@ -410,14 +409,14 @@ void merkleMetaAsExpected() { } @Test - void doesntThrowWhenDualStateIsNull() { + void doesntThrowWhenPlatformStateIsNull() { subject.setChild(StateChildIndices.SPECIAL_FILES, specialFiles); subject.setChild(StateChildIndices.NETWORK_CTX, networkContext); subject.setChild(StateChildIndices.ACCOUNTS, accounts); given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(app.stakeStartupHelper()).willReturn(stakeStartupHelper); @@ -445,7 +444,7 @@ void genesisInitCreatesChildren() { // and: given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(platform.getAddressBook()).willReturn(addressBook); given(app.sysAccountsCreator()).willReturn(accountsCreator); @@ -463,7 +462,7 @@ void genesisInitCreatesChildren() { // when: subject = tracked(new ServicesState()); - subject.init(platform, dualState, InitTrigger.GENESIS, null); + subject.init(platform, platformState, InitTrigger.GENESIS, null); // then: assertFalse(subject.isImmutable()); @@ -483,7 +482,7 @@ void genesisInitCreatesChildren() { assertEquals(1001L, subject.networkCtx().seqNo().current()); assertNotNull(subject.specialFiles()); // and: - verify(dualStateAccessor).setDualState(dualState); + verify(platformStateAccessor).setPlatformState(platformState); verify(initFlow).runWith(eq(subject), any()); verify(appBuilder).bootstrapProps(any()); verify(appBuilder).initialHash(EMPTY_HASH); @@ -526,7 +525,7 @@ void genesisInitRespectsSelectedOnDiskMapsAndConsolidatedRecords() { // and: given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(platform.getAddressBook()).willReturn(addressBook); given(app.sysAccountsCreator()).willReturn(accountsCreator); @@ -541,7 +540,7 @@ void genesisInitRespectsSelectedOnDiskMapsAndConsolidatedRecords() { .getNodeId(anyInt()); // when: - subject.init(platform, dualState, InitTrigger.GENESIS, null); + subject.init(platform, platformState, InitTrigger.GENESIS, null); // then: assertTrue(subject.uniqueTokens().isVirtual()); @@ -559,7 +558,7 @@ void nonGenesisInitReusesContextIfPresent() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(platform.getAddressBook()).willReturn(addressBook); given(app.maybeNewRecoveredStateListener()).willReturn(Optional.of(recoveredStateListener)); @@ -568,7 +567,7 @@ void nonGenesisInitReusesContextIfPresent() { APPS.save(selfId, app); // when: - subject.init(platform, dualState, RECONNECT, currentVersion); + subject.init(platform, platformState, RECONNECT, currentVersion); // then: assertSame(addressBook, subject.addressBook()); @@ -589,12 +588,12 @@ void nonGenesisInitExitsIfStateVersionLaterThanCurrentSoftware() { given(platform.getSelfId()).willReturn(selfId); given(app.systemExits()).willReturn(mockExit); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); // and: APPS.save(selfId, app); // when: - subject.init(platform, dualState, RESTART, futureVersion); + subject.init(platform, platformState, RESTART, futureVersion); verify(mockExit).fail(1); } @@ -607,7 +606,7 @@ void nonGenesisInitDoesNotClearPreparedUpgradeIfSameVersion() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(app.stakeStartupHelper()).willReturn(stakeStartupHelper); @@ -615,7 +614,7 @@ void nonGenesisInitDoesNotClearPreparedUpgradeIfSameVersion() { APPS.save(selfId, app); // when: - subject.init(platform, dualState, RESTART, currentVersion); + subject.init(platform, platformState, RESTART, currentVersion); verify(networkContext, never()).discardPreparedUpgradeMeta(); } @@ -638,7 +637,7 @@ void nonGenesisInitWithBuildDoesntRunMigrations() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(app.stakeStartupHelper()).willReturn(stakeStartupHelper); @@ -647,7 +646,7 @@ void nonGenesisInitWithBuildDoesntRunMigrations() { // when: - subject.init(platform, dualState, RESTART, configVersion); + subject.init(platform, platformState, RESTART, configVersion); verify(networkContext, never()).discardPreparedUpgradeMeta(); } @@ -664,7 +663,7 @@ void nonGenesisInitClearsPreparedUpgradeIfDeployedIsLaterVersion() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(app.stakeStartupHelper()).willReturn(stakeStartupHelper); @@ -672,7 +671,7 @@ void nonGenesisInitClearsPreparedUpgradeIfDeployedIsLaterVersion() { APPS.save(selfId, app); // when: - subject.init(platform, dualState, RESTART, justPriorVersion); + subject.init(platform, platformState, RESTART, justPriorVersion); verify(networkContext).discardPreparedUpgradeMeta(); unmockMigrators(); @@ -691,7 +690,7 @@ void nonGenesisInitWithOldVersionMarksMigrationRecordsNotStreamed() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(app.stakeStartupHelper()).willReturn(stakeStartupHelper); @@ -699,7 +698,7 @@ void nonGenesisInitWithOldVersionMarksMigrationRecordsNotStreamed() { APPS.save(selfId, app); // when: - subject.init(platform, dualState, RESTART, justPriorVersion); + subject.init(platform, platformState, RESTART, justPriorVersion); verify(networkContext).discardPreparedUpgradeMeta(); verify(networkContext).markMigrationRecordsNotYetStreamed(); @@ -711,7 +710,7 @@ void nonGenesisInitWithOldVersionMarksMigrationRecordsNotStreamed() { void nonGenesisInitThrowsWithUnsupportedStateVersionUsed() { subject.setDeserializedStateVersion(StateVersions.RELEASE_0310_VERSION - 1); - assertThrows(IllegalStateException.class, () -> subject.init(platform, dualState, RESTART, null)); + assertThrows(IllegalStateException.class, () -> subject.init(platform, platformState, RESTART, null)); } @Test @@ -722,13 +721,13 @@ void nonGenesisInitDoesntClearPreparedUpgradeIfNotUpgrade() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); // and: APPS.save(selfId, app); // when: - subject.init(platform, dualState, RECONNECT, currentVersion); + subject.init(platform, platformState, RECONNECT, currentVersion); verify(networkContext, never()).discardPreparedUpgradeMeta(); } @@ -756,7 +755,7 @@ void nonGenesisInitConsolidatesRecords() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(platform.getAddressBook()).willReturn(addressBook); @@ -765,7 +764,7 @@ void nonGenesisInitConsolidatesRecords() { APPS.save(selfId, app); // when: - subject.init(platform, dualState, RESTART, currentVersion); + subject.init(platform, platformState, RESTART, currentVersion); verify(recordConsolidator).consolidateRecordsToSingleFcq(subject); ServicesState.setRecordConsolidator(RecordConsolidation::toSingleFcq); @@ -797,7 +796,7 @@ void nonGenesisInitHandlesNftMigration() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(platform.getAddressBook()).willReturn(addressBook); @@ -806,7 +805,7 @@ void nonGenesisInitHandlesNftMigration() { APPS.save(selfId, app); // when: - subject.init(platform, dualState, RESTART, currentVersion); + subject.init(platform, platformState, RESTART, currentVersion); verify(mapToDiskMigration) .migrateToDiskAsApropos( INSERTIONS_PER_COPY, @@ -846,7 +845,7 @@ void nonGenesisInitHandlesTokenRelMigrationToDisk() { given(app.hashLogger()).willReturn(hashLogger); given(app.initializationFlow()).willReturn(initFlow); - given(app.dualStateAccessor()).willReturn(dualStateAccessor); + given(app.platformStateAccessor()).willReturn(platformStateAccessor); given(platform.getSelfId()).willReturn(selfId); given(platform.getAddressBook()).willReturn(addressBook); @@ -855,7 +854,7 @@ void nonGenesisInitHandlesTokenRelMigrationToDisk() { APPS.save(selfId, app); // when: - subject.init(platform, dualState, RESTART, currentVersion); + subject.init(platform, platformState, RESTART, currentVersion); verify(mapToDiskMigration) .migrateToDiskAsApropos( INSERTIONS_PER_COPY, @@ -939,7 +938,7 @@ void testGenesisState() { final var app = createApp(platform); APPS.save(platform.getSelfId(), app); - assertDoesNotThrow(() -> servicesState.init(platform, new DualStateImpl(), InitTrigger.GENESIS, null)); + assertDoesNotThrow(() -> servicesState.init(platform, new PlatformState(), InitTrigger.GENESIS, null)); } @Test diff --git a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/DualStateAccessorTest.java b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/PlatformStateAccessorTest.java similarity index 75% rename from hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/DualStateAccessorTest.java rename to hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/PlatformStateAccessorTest.java index 4a29cb338bdf..0a80dba5ab69 100644 --- a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/DualStateAccessorTest.java +++ b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/PlatformStateAccessorTest.java @@ -18,7 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; -import com.swirlds.platform.system.SwirldDualState; +import com.swirlds.platform.state.PlatformState; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -26,22 +26,22 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -class DualStateAccessorTest { +class PlatformStateAccessorTest { @Mock - private SwirldDualState dualState; + private PlatformState platformState; @Test void beanMethodsWork() { // setup: - final var subject = new DualStateAccessor(); + final var subject = new PlatformStateAccessor(); // expect: - assertNull(subject.getDualState()); + assertNull(subject.getPlatformState()); // and when: - subject.setDualState(dualState); + subject.setPlatformState(platformState); // expect: - Assertions.assertSame(dualState, subject.getDualState()); + Assertions.assertSame(platformState, subject.getPlatformState()); } } diff --git a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/logic/BlockManagerTest.java b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/logic/BlockManagerTest.java index 8acc2c8be62c..3be36c6b7ec3 100644 --- a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/logic/BlockManagerTest.java +++ b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/logic/BlockManagerTest.java @@ -31,13 +31,13 @@ import static org.mockito.Mockito.verify; import com.hedera.node.app.service.mono.context.properties.BootstrapProperties; -import com.hedera.node.app.service.mono.state.DualStateAccessor; +import com.hedera.node.app.service.mono.state.PlatformStateAccessor; import com.hedera.node.app.service.mono.state.merkle.MerkleNetworkContext; import com.hedera.node.app.service.mono.stream.RecordsRunningHashLeaf; import com.hedera.test.utils.TxnUtils; import com.swirlds.common.crypto.Hash; import com.swirlds.common.crypto.RunningHash; -import com.swirlds.platform.system.SwirldDualState; +import com.swirlds.platform.state.PlatformState; import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -60,10 +60,10 @@ class BlockManagerTest { @Mock private RecordsRunningHashLeaf runningHashLeaf; - private DualStateAccessor dualStateAccessor; + private PlatformStateAccessor platformStateAccessor; @Mock - private SwirldDualState dualState; + private PlatformState platformState; private BlockManager subject; @@ -71,9 +71,10 @@ class BlockManagerTest { void setUp() { given(bootstrapProperties.getLongProperty(HEDERA_RECORD_STREAM_LOG_PERIOD)) .willReturn(blockPeriodSecs); - dualStateAccessor = new DualStateAccessor(); - dualStateAccessor.setDualState(dualState); - subject = new BlockManager(bootstrapProperties, () -> networkContext, () -> runningHashLeaf, dualStateAccessor); + platformStateAccessor = new PlatformStateAccessor(); + platformStateAccessor.setPlatformState(platformState); + subject = new BlockManager( + bootstrapProperties, () -> networkContext, () -> runningHashLeaf, platformStateAccessor); } @Test @@ -175,39 +176,39 @@ void computesNewBlockIfIsFirstTransactionAfterFreezeRestart() throws Interrupted given(networkContext.firstConsTimeOfCurrentBlock()).willReturn(aTime); given(runningHashLeaf.currentRunningHash()).willReturn(aFullBlockHash); given(networkContext.getAlignmentBlockNo()).willReturn(someBlockNo); - given(dualState.getLastFrozenTime()).willReturn(aTime); - given(dualState.getFreezeTime()).willReturn(aTime); + given(platformState.getLastFrozenTime()).willReturn(aTime); + given(platformState.getFreezeTime()).willReturn(aTime); final var values = subject.computeBlockValues(someTime, gasLimit); assertEquals(someBlockNo + 1, values.getNumber()); - verify(dualState).setFreezeTime(null); + verify(platformState).setFreezeTime(null); } @Test void computesSameBlockIfPastAndCurrentFreezeTimeAreNull() { given(networkContext.firstConsTimeOfCurrentBlock()).willReturn(aTime); given(networkContext.getAlignmentBlockNo()).willReturn(someBlockNo); - given(dualState.getFreezeTime()).willReturn(null); - Mockito.lenient().when(dualState.getLastFrozenTime()).thenReturn(null); + given(platformState.getFreezeTime()).willReturn(null); + Mockito.lenient().when(platformState.getLastFrozenTime()).thenReturn(null); final var values = subject.computeBlockValues(someTime, gasLimit); assertEquals(someBlockNo, values.getNumber()); - verify(dualState, never()).setFreezeTime(null); + verify(platformState, never()).setFreezeTime(null); } @Test void computesSameBlockIfPastAndCurrentFreezeTimeDontMatch() { given(networkContext.firstConsTimeOfCurrentBlock()).willReturn(aTime); given(networkContext.getAlignmentBlockNo()).willReturn(someBlockNo); - given(dualState.getLastFrozenTime()).willReturn(aTime); - given(dualState.getFreezeTime()).willReturn(anotherTime); + given(platformState.getLastFrozenTime()).willReturn(aTime); + given(platformState.getFreezeTime()).willReturn(anotherTime); final var values = subject.computeBlockValues(someTime, gasLimit); assertEquals(someBlockNo, values.getNumber()); - verify(dualState, never()).setFreezeTime(null); + verify(platformState, never()).setFreezeTime(null); } @Test diff --git a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/merkle/MerkleNetworkContextTest.java b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/merkle/MerkleNetworkContextTest.java index 16db7aef4c25..a6903ce79456 100644 --- a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/merkle/MerkleNetworkContextTest.java +++ b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/state/merkle/MerkleNetworkContextTest.java @@ -50,7 +50,7 @@ import com.hedera.node.app.hapi.utils.throttles.DeterministicThrottle; import com.hedera.node.app.hapi.utils.throttles.GasLimitDeterministicThrottle; import com.hedera.node.app.service.mono.fees.congestion.MultiplierSources; -import com.hedera.node.app.service.mono.state.DualStateAccessor; +import com.hedera.node.app.service.mono.state.PlatformStateAccessor; import com.hedera.node.app.service.mono.state.merkle.internals.BytesElement; import com.hedera.node.app.service.mono.state.submerkle.ExchangeRates; import com.hedera.node.app.service.mono.state.submerkle.SequenceNumber; @@ -66,7 +66,7 @@ import com.swirlds.base.state.MutabilityException; import com.swirlds.common.crypto.Hash; import com.swirlds.fcqueue.FCQueue; -import com.swirlds.platform.state.DualStateImpl; +import com.swirlds.platform.state.PlatformState; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.time.Instant; @@ -534,7 +534,7 @@ void summarizesHashesAsExpected() { @Test void summarizesStateVersionAsExpected() { throttling = mock(FunctionalityThrottling.class); - final var accessor = mock(DualStateAccessor.class); + final var accessor = mock(PlatformStateAccessor.class); given(throttling.allActiveThrottles()).willReturn(activeThrottles()); given(throttling.gasLimitThrottle()).willReturn(gasLimitDeterministicThrottle); @@ -656,10 +656,10 @@ void summarizesPendingUpdateAsExpected() { final var someTime = Instant.ofEpochSecond(1_234_567L, 890); throttling = mock(FunctionalityThrottling.class); - final var dualState = mock(DualStateImpl.class); - final var accessor = mock(DualStateAccessor.class); + final var platformState = mock(PlatformState.class); + final var accessor = mock(PlatformStateAccessor.class); - given(accessor.getDualState()).willReturn(dualState); + given(accessor.getPlatformState()).willReturn(platformState); // and: final var desiredWithPreparedUnscheduledMaintenance = "The network context (state version 13) is,\n" @@ -728,7 +728,7 @@ void summarizesPendingUpdateAsExpected() { // then: assertEquals(desiredWithPreparedUnscheduledMaintenance, subject.summarizedWith(accessor)); - given(dualState.getFreezeTime()).willReturn(someTime); + given(platformState.getFreezeTime()).willReturn(someTime); assertEquals(desiredWithPreparedAndScheduledMaintenance, subject.summarizedWith(accessor)); } diff --git a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/txns/network/UpgradeActionsTest.java b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/txns/network/UpgradeActionsTest.java index 915285226e5d..6f8027f020da 100644 --- a/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/txns/network/UpgradeActionsTest.java +++ b/hedera-node/hedera-mono-service/src/test/java/com/hedera/node/app/service/mono/txns/network/UpgradeActionsTest.java @@ -41,7 +41,7 @@ import com.hedera.test.extensions.LoggingTarget; import com.hedera.test.utils.IdUtils; import com.hedera.test.utils.TestFileUtils; -import com.swirlds.platform.state.DualStateImpl; +import com.swirlds.platform.state.PlatformState; import edu.umd.cs.findbugs.annotations.Nullable; import java.io.File; import java.io.IOException; @@ -76,7 +76,7 @@ class UpgradeActionsTest { private GlobalDynamicProperties dynamicProperties; @Mock - private DualStateImpl dualState; + private PlatformState platformState; @Mock private UpgradeActions.UnzipAction unzipAction; @@ -101,7 +101,7 @@ void setUp() { noiseSubFileLoc = TestFileUtils.toPath(markerFilesLoc, "edargpu"); subject = new UpgradeActions( - unzipAction, dynamicProperties, () -> dualState, () -> specialFiles, () -> networkCtx); + unzipAction, dynamicProperties, () -> platformState, () -> specialFiles, () -> networkCtx); } @AfterEach @@ -141,8 +141,8 @@ void catchesUpOnUpgradePreparationIfInContext() throws IOException { given(networkCtx.getPreparedUpdateFileNum()).willReturn(150L); given(specialFiles.get(IdUtils.asFile("0.0.150"))).willReturn(PRETEND_ARCHIVE); given(dynamicProperties.upgradeArtifactsLoc()).willReturn(markerFilesLoc); - given(dualState.getFreezeTime()).willReturn(then); - given(dualState.getLastFrozenTime()).willReturn(then); + given(platformState.getFreezeTime()).willReturn(then); + given(platformState.getLastFrozenTime()).willReturn(then); assertTrue(new File(markerFilesLoc).mkdirs()); subject.catchUpOnMissedSideEffects(); @@ -163,14 +163,14 @@ void catchUpIsNoopWithNothingToDo() { "Should not create " + EXEC_IMMEDIATE_MARKER + " if no prepared upgrade in state"); assertFalse( Paths.get(markerFilesLoc, FREEZE_SCHEDULED_MARKER).toFile().exists(), - "Should not create " + FREEZE_SCHEDULED_MARKER + " if dual freeze time is null"); + "Should not create " + FREEZE_SCHEDULED_MARKER + " if platform freeze time is null"); } @Test - void doesntCatchUpOnFreezeScheduleIfInDualAndNoUpgradeIsPrepared() { + void doesntCatchUpOnFreezeScheduleIfInPlatformStateAndNoUpgradeIsPrepared() { rmIfPresent(FREEZE_SCHEDULED_MARKER); - given(dualState.getFreezeTime()).willReturn(then); + given(platformState.getFreezeTime()).willReturn(then); subject.catchUpOnMissedSideEffects(); @@ -180,10 +180,10 @@ void doesntCatchUpOnFreezeScheduleIfInDualAndNoUpgradeIsPrepared() { } @Test - void catchesUpOnFreezeScheduleIfInDualAndUpgradeIsPrepared() throws IOException { + void catchesUpOnFreezeScheduleIfInPlatformStateAndUpgradeIsPrepared() throws IOException { rmIfPresent(FREEZE_SCHEDULED_MARKER); - given(dualState.getFreezeTime()).willReturn(then); + given(platformState.getFreezeTime()).willReturn(then); given(networkCtx.hasPreparedUpgrade()).willReturn(true); given(dynamicProperties.upgradeArtifactsLoc()).willReturn(markerFilesLoc); @@ -197,17 +197,17 @@ void freezeCatchUpWritesNoMarkersIfJustUnfrozen() { rmIfPresent(FREEZE_ABORTED_MARKER); rmIfPresent(FREEZE_SCHEDULED_MARKER); - given(dualState.getFreezeTime()).willReturn(then); - given(dualState.getLastFrozenTime()).willReturn(then); + given(platformState.getFreezeTime()).willReturn(then); + given(platformState.getLastFrozenTime()).willReturn(then); subject.catchUpOnMissedSideEffects(); assertFalse( Paths.get(markerFilesLoc, FREEZE_ABORTED_MARKER).toFile().exists(), - "Should not create " + FREEZE_ABORTED_MARKER + " if dual last frozen time is freeze time"); + "Should not create " + FREEZE_ABORTED_MARKER + " if platform last frozen time is freeze time"); assertFalse( Paths.get(markerFilesLoc, FREEZE_SCHEDULED_MARKER).toFile().exists(), - "Should not create " + FREEZE_SCHEDULED_MARKER + " if dual last frozen time is freeze time"); + "Should not create " + FREEZE_SCHEDULED_MARKER + " if platform last frozen time is freeze time"); } @Test @@ -302,7 +302,7 @@ void setsExpectedFreezeAndWritesMarkerForFreezeUpgrade() throws IOException { subject.scheduleFreezeUpgradeAt(then); - verify(dualState).setFreezeTime(then); + verify(platformState).setFreezeTime(then); assertMarkerCreated(FREEZE_SCHEDULED_MARKER, then); } @@ -313,7 +313,7 @@ void setsExpectedFreezeOnlyForFreezeOnly() { subject.scheduleFreezeOnlyAt(then); - verify(dualState).setFreezeTime(then); + verify(platformState).setFreezeTime(then); assertFalse( Paths.get(markerFilesLoc, FREEZE_SCHEDULED_MARKER).toFile().exists(), @@ -321,14 +321,14 @@ void setsExpectedFreezeOnlyForFreezeOnly() { } @Test - void nullsOutDualOnAborting() throws IOException { + void nullsOutPlatformStateOnAborting() throws IOException { rmIfPresent(FREEZE_ABORTED_MARKER); given(dynamicProperties.upgradeArtifactsLoc()).willReturn(markerFilesLoc); subject.abortScheduledFreeze(); - verify(dualState).setFreezeTime(null); + verify(platformState).setFreezeTime(null); assertMarkerCreated(FREEZE_ABORTED_MARKER, null); } @@ -346,7 +346,7 @@ void canStillWriteMarkersEvenIfDirDoesntExist() throws IOException { subject.abortScheduledFreeze(); - verify(dualState).setFreezeTime(null); + verify(platformState).setFreezeTime(null); assertMarkerCreated(FREEZE_ABORTED_MARKER, null, otherMarkerFilesLoc); @@ -367,7 +367,7 @@ void complainsLoudlyWhenUnableToWriteMarker() throws IOException { subject.abortScheduledFreeze(); - verify(dualState).setFreezeTime(null); + verify(platformState).setFreezeTime(null); assertThat( logCaptor.errorLogs(), @@ -380,7 +380,7 @@ void complainsLoudlyWhenUnableToWriteMarker() throws IOException { void determinesIfFreezeIsScheduled() { assertFalse(subject.isFreezeScheduled()); - given(dualState.getFreezeTime()).willReturn(then); + given(platformState.getFreezeTime()).willReturn(then); assertTrue(subject.isFreezeScheduled()); } diff --git a/platform-sdk/platform-apps/demos/CryptocurrencyDemo/src/main/java/com/swirlds/demo/crypto/CryptocurrencyDemoState.java b/platform-sdk/platform-apps/demos/CryptocurrencyDemo/src/main/java/com/swirlds/demo/crypto/CryptocurrencyDemoState.java index a197053446c8..22fae2700dac 100644 --- a/platform-sdk/platform-apps/demos/CryptocurrencyDemo/src/main/java/com/swirlds/demo/crypto/CryptocurrencyDemoState.java +++ b/platform-sdk/platform-apps/demos/CryptocurrencyDemo/src/main/java/com/swirlds/demo/crypto/CryptocurrencyDemoState.java @@ -32,11 +32,11 @@ import com.swirlds.common.merkle.impl.PartialMerkleLeaf; import com.swirlds.common.platform.NodeId; import com.swirlds.platform.SwirldsPlatform; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.address.Address; import com.swirlds.platform.system.address.AddressBook; @@ -199,7 +199,7 @@ public synchronized CryptocurrencyDemoState copy() { } @Override - public void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) { + public void handleConsensusRound(final Round round, final PlatformState swirldDualState) { throwIfImmutable(); round.forEachEventTransaction( (event, transaction) -> handleTransaction(event.getCreatorId(), true, transaction)); @@ -377,7 +377,7 @@ public void genesisInit() { @Override public void init( final Platform platform, - final SwirldDualState swirldDualState, + final PlatformState swirldDualState, final InitTrigger trigger, final SoftwareVersion previousSoftwareVersion) { this.platform = (SwirldsPlatform) platform; diff --git a/platform-sdk/platform-apps/demos/HashgraphDemo/src/main/java/com/swirlds/demo/hashgraph/HashgraphDemoState.java b/platform-sdk/platform-apps/demos/HashgraphDemo/src/main/java/com/swirlds/demo/hashgraph/HashgraphDemoState.java index 36cb3f012c29..60858a6c7dc5 100644 --- a/platform-sdk/platform-apps/demos/HashgraphDemo/src/main/java/com/swirlds/demo/hashgraph/HashgraphDemoState.java +++ b/platform-sdk/platform-apps/demos/HashgraphDemo/src/main/java/com/swirlds/demo/hashgraph/HashgraphDemoState.java @@ -30,8 +30,8 @@ import com.swirlds.common.io.streams.SerializableDataOutputStream; import com.swirlds.common.merkle.MerkleLeaf; import com.swirlds.common.merkle.impl.PartialMerkleLeaf; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; /** @@ -67,7 +67,7 @@ private HashgraphDemoState(final HashgraphDemoState sourceState) { } @Override - public synchronized void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) {} + public synchronized void handleConsensusRound(final Round round, final PlatformState platformState) {} /** * {@inheritDoc} diff --git a/platform-sdk/platform-apps/demos/HelloSwirldDemo/src/main/java/com/swirlds/demo/hello/HelloSwirldDemoState.java b/platform-sdk/platform-apps/demos/HelloSwirldDemo/src/main/java/com/swirlds/demo/hello/HelloSwirldDemoState.java index 050620793fc5..103fce8f360c 100644 --- a/platform-sdk/platform-apps/demos/HelloSwirldDemo/src/main/java/com/swirlds/demo/hello/HelloSwirldDemoState.java +++ b/platform-sdk/platform-apps/demos/HelloSwirldDemo/src/main/java/com/swirlds/demo/hello/HelloSwirldDemoState.java @@ -30,8 +30,8 @@ import com.swirlds.common.io.streams.SerializableDataOutputStream; import com.swirlds.common.merkle.MerkleLeaf; import com.swirlds.common.merkle.impl.PartialMerkleLeaf; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.transaction.Transaction; import java.io.IOException; @@ -99,7 +99,7 @@ private HelloSwirldDemoState(final HelloSwirldDemoState sourceState) { } @Override - public synchronized void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) { + public synchronized void handleConsensusRound(final Round round, final PlatformState platformState) { throwIfImmutable(); round.forEachTransaction(this::handleTransaction); } diff --git a/platform-sdk/platform-apps/demos/StatsDemo/src/main/java/com/swirlds/demo/stats/StatsDemoState.java b/platform-sdk/platform-apps/demos/StatsDemo/src/main/java/com/swirlds/demo/stats/StatsDemoState.java index b40d1ccb957a..dfccdacf9caf 100644 --- a/platform-sdk/platform-apps/demos/StatsDemo/src/main/java/com/swirlds/demo/stats/StatsDemoState.java +++ b/platform-sdk/platform-apps/demos/StatsDemo/src/main/java/com/swirlds/demo/stats/StatsDemoState.java @@ -30,8 +30,8 @@ import com.swirlds.common.io.streams.SerializableDataOutputStream; import com.swirlds.common.merkle.MerkleLeaf; import com.swirlds.common.merkle.impl.PartialMerkleLeaf; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; /** @@ -69,7 +69,7 @@ private StatsDemoState(final StatsDemoState sourceState) { } @Override - public void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) {} + public void handleConsensusRound(final Round round, final PlatformState platformState) {} /** * {@inheritDoc} diff --git a/platform-sdk/platform-apps/tests/AddressBookTestingTool/src/main/java/com/swirlds/demo/addressbook/AddressBookTestingToolState.java b/platform-sdk/platform-apps/tests/AddressBookTestingTool/src/main/java/com/swirlds/demo/addressbook/AddressBookTestingToolState.java index 2e1def946d93..fe5c26fbc3ad 100644 --- a/platform-sdk/platform-apps/tests/AddressBookTestingTool/src/main/java/com/swirlds/demo/addressbook/AddressBookTestingToolState.java +++ b/platform-sdk/platform-apps/tests/AddressBookTestingTool/src/main/java/com/swirlds/demo/addressbook/AddressBookTestingToolState.java @@ -44,11 +44,11 @@ import com.swirlds.common.utility.ByteUtils; import com.swirlds.common.utility.StackTrace; import com.swirlds.platform.config.AddressBookConfig; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.address.Address; import com.swirlds.platform.system.address.AddressBook; @@ -109,8 +109,8 @@ private static class ClassVersion { /** * The number of rounds handled by this app. Is incremented each time - * {@link #handleConsensusRound(Round, SwirldDualState)} is called. Note that this may not actually equal the round - * number, since we don't call {@link #handleConsensusRound(Round, SwirldDualState)} for rounds with no events. + * {@link #handleConsensusRound(Round, PlatformState)} is called. Note that this may not actually equal the round + * number, since we don't call {@link #handleConsensusRound(Round, PlatformState)} for rounds with no events. * *

* Affects the hash of this node. @@ -161,11 +161,11 @@ public synchronized AddressBookTestingToolState copy() { @Override public void init( @NonNull final Platform platform, - @NonNull final SwirldDualState swirldDualState, + @NonNull final PlatformState platformState, @NonNull final InitTrigger trigger, @Nullable final SoftwareVersion previousSoftwareVersion) { Objects.requireNonNull(platform, "the platform cannot be null"); - Objects.requireNonNull(swirldDualState, "the swirld dual state cannot be null"); + Objects.requireNonNull(platformState, "the platform state cannot be null"); Objects.requireNonNull(trigger, "the init trigger cannot be null"); addressBookConfig = platform.getContext().getConfiguration().getConfigData(AddressBookConfig.class); testingToolConfig = platform.getContext().getConfiguration().getConfigData(AddressBookTestingToolConfig.class); @@ -184,9 +184,9 @@ public void init( * {@inheritDoc} */ @Override - public void handleConsensusRound(@NonNull final Round round, @NonNull final SwirldDualState swirldDualState) { + public void handleConsensusRound(@NonNull final Round round, @NonNull final PlatformState platformState) { Objects.requireNonNull(round, "the round cannot be null"); - Objects.requireNonNull(swirldDualState, "the swirld dual state cannot be null"); + Objects.requireNonNull(platformState, "the platform state cannot be null"); throwIfImmutable(); if (roundsHandled == 0 && !freezeAfterGenesis.equals(Duration.ZERO)) { @@ -195,7 +195,7 @@ public void handleConsensusRound(@NonNull final Round round, @NonNull final Swir STARTUP.getMarker(), "Setting freeze time to {} seconds after genesis.", freezeAfterGenesis.getSeconds()); - swirldDualState.setFreezeTime(round.getConsensusTimestamp().plus(freezeAfterGenesis)); + platformState.setFreezeTime(round.getConsensusTimestamp().plus(freezeAfterGenesis)); } roundsHandled++; diff --git a/platform-sdk/platform-apps/tests/ConsistencyTestingTool/src/main/java/com/swirlds/demo/consistency/ConsistencyTestingToolState.java b/platform-sdk/platform-apps/tests/ConsistencyTestingTool/src/main/java/com/swirlds/demo/consistency/ConsistencyTestingToolState.java index 570f73a283e5..44b241e5682c 100644 --- a/platform-sdk/platform-apps/tests/ConsistencyTestingTool/src/main/java/com/swirlds/demo/consistency/ConsistencyTestingToolState.java +++ b/platform-sdk/platform-apps/tests/ConsistencyTestingTool/src/main/java/com/swirlds/demo/consistency/ConsistencyTestingToolState.java @@ -26,11 +26,11 @@ import com.swirlds.common.merkle.MerkleLeaf; import com.swirlds.common.merkle.impl.PartialMerkleLeaf; import com.swirlds.common.utility.NonCryptographicHashing; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.events.Event; import com.swirlds.platform.system.transaction.ConsensusTransaction; @@ -75,8 +75,8 @@ private static class ClassVersion { /** * The number of rounds handled by this app. Is incremented each time - * {@link #handleConsensusRound(Round, SwirldDualState)} is called. Note that this may not actually equal the round - * number, since we don't call {@link #handleConsensusRound(Round, SwirldDualState)} for rounds with no events. + * {@link #handleConsensusRound(Round, PlatformState)} is called. Note that this may not actually equal the round + * number, since we don't call {@link #handleConsensusRound(Round, PlatformState)} for rounds with no events. * *

* Affects the hash of this node. @@ -130,12 +130,12 @@ private ConsistencyTestingToolState(@NonNull final ConsistencyTestingToolState t @Override public void init( @NonNull final Platform platform, - @NonNull final SwirldDualState swirldDualState, + @NonNull final PlatformState platformState, @NonNull final InitTrigger trigger, @Nullable final SoftwareVersion previousSoftwareVersion) { Objects.requireNonNull(platform); - Objects.requireNonNull(swirldDualState); + Objects.requireNonNull(platformState); Objects.requireNonNull(trigger); final StateConfig stateConfig = platform.getContext().getConfiguration().getConfigData(StateConfig.class); @@ -242,9 +242,9 @@ public void preHandle(@NonNull final Event event) { * Writes the round and its contents to a log on disk */ @Override - public void handleConsensusRound(final @NonNull Round round, final @NonNull SwirldDualState swirldDualState) { + public void handleConsensusRound(final @NonNull Round round, final @NonNull PlatformState platformState) { Objects.requireNonNull(round); - Objects.requireNonNull(swirldDualState); + Objects.requireNonNull(platformState); if (roundsHandled == 0 && !freezeAfterGenesis.equals(Duration.ZERO)) { // This is the first round after genesis. @@ -252,7 +252,7 @@ public void handleConsensusRound(final @NonNull Round round, final @NonNull Swir STARTUP.getMarker(), "Setting freeze time to {} seconds after genesis.", freezeAfterGenesis.getSeconds()); - swirldDualState.setFreezeTime(round.getConsensusTimestamp().plus(freezeAfterGenesis)); + platformState.setFreezeTime(round.getConsensusTimestamp().plus(freezeAfterGenesis)); } roundsHandled++; diff --git a/platform-sdk/platform-apps/tests/ISSTestingTool/src/main/java/com/swirlds/demo/iss/ISSTestingToolState.java b/platform-sdk/platform-apps/tests/ISSTestingTool/src/main/java/com/swirlds/demo/iss/ISSTestingToolState.java index a8b51334be6a..74c067ab2da7 100644 --- a/platform-sdk/platform-apps/tests/ISSTestingTool/src/main/java/com/swirlds/demo/iss/ISSTestingToolState.java +++ b/platform-sdk/platform-apps/tests/ISSTestingTool/src/main/java/com/swirlds/demo/iss/ISSTestingToolState.java @@ -40,11 +40,11 @@ import com.swirlds.common.platform.NodeId; import com.swirlds.common.scratchpad.Scratchpad; import com.swirlds.common.utility.ByteUtils; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.address.Address; import com.swirlds.platform.system.address.AddressBook; @@ -149,7 +149,7 @@ public synchronized ISSTestingToolState copy() { @Override public void init( final Platform platform, - final SwirldDualState swirldDualState, + final PlatformState platformState, final InitTrigger trigger, final SoftwareVersion previousSoftwareVersion) { @@ -173,7 +173,7 @@ public void init( * {@inheritDoc} */ @Override - public void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) { + public void handleConsensusRound(final Round round, final PlatformState platformState) { throwIfImmutable(); final Iterator eventIterator = round.iterator(); diff --git a/platform-sdk/platform-apps/tests/MigrationTestingTool/src/main/java/com/swirlds/demo/migration/MigrationTestingToolState.java b/platform-sdk/platform-apps/tests/MigrationTestingTool/src/main/java/com/swirlds/demo/migration/MigrationTestingToolState.java index 548edd45f9d4..298bc4434628 100644 --- a/platform-sdk/platform-apps/tests/MigrationTestingTool/src/main/java/com/swirlds/demo/migration/MigrationTestingToolState.java +++ b/platform-sdk/platform-apps/tests/MigrationTestingTool/src/main/java/com/swirlds/demo/migration/MigrationTestingToolState.java @@ -33,11 +33,11 @@ import com.swirlds.merkledb.MerkleDb; import com.swirlds.merkledb.MerkleDbDataSourceBuilder; import com.swirlds.merkledb.MerkleDbTableConfig; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.address.AddressBook; import com.swirlds.platform.system.events.ConsensusEvent; @@ -224,7 +224,7 @@ private void genesisInit(final Platform platform) { @Override public void init( final Platform platform, - final SwirldDualState swirldDualState, + final PlatformState platformState, final InitTrigger trigger, final SoftwareVersion previousSoftwareVersion) { @@ -274,7 +274,7 @@ private static MigrationTestingToolTransaction parseTransaction(final Transactio * {@inheritDoc} */ @Override - public void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) { + public void handleConsensusRound(final Round round, final PlatformState platformState) { throwIfImmutable(); for (final Iterator eventIt = round.iterator(); eventIt.hasNext(); ) { final ConsensusEvent event = eventIt.next(); diff --git a/platform-sdk/platform-apps/tests/PlatformTestingTool/src/main/java/com/swirlds/demo/platform/PlatformTestingToolState.java b/platform-sdk/platform-apps/tests/PlatformTestingTool/src/main/java/com/swirlds/demo/platform/PlatformTestingToolState.java index fbe86a209efe..44a12e872190 100644 --- a/platform-sdk/platform-apps/tests/PlatformTestingTool/src/main/java/com/swirlds/demo/platform/PlatformTestingToolState.java +++ b/platform-sdk/platform-apps/tests/PlatformTestingTool/src/main/java/com/swirlds/demo/platform/PlatformTestingToolState.java @@ -70,11 +70,11 @@ import com.swirlds.merkle.map.test.pta.MapKey; import com.swirlds.platform.ParameterProvider; import com.swirlds.platform.Utilities; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.address.AddressBook; import com.swirlds.platform.system.events.ConsensusEvent; @@ -1037,9 +1037,9 @@ private void handleControlTransaction( /** * Handle the freeze transaction type. */ - private void handleFreezeTransaction(final TestTransaction testTransaction, final SwirldDualState swirldDualState) { + private void handleFreezeTransaction(final TestTransaction testTransaction, final PlatformState platformState) { final FreezeTransaction freezeTx = testTransaction.getFreezeTransaction(); - FreezeTransactionHandler.freeze(freezeTx, swirldDualState); + FreezeTransactionHandler.freeze(freezeTx, platformState); } /** @@ -1057,7 +1057,7 @@ protected void preHandleTransaction(final Transaction transaction) { } @Override - public synchronized void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) { + public synchronized void handleConsensusRound(final Round round, final PlatformState platformState) { throwIfImmutable(); if (!initialized.get()) { throw new IllegalStateException("handleConsensusRound() called before init()"); @@ -1065,7 +1065,7 @@ public synchronized void handleConsensusRound(final Round round, final SwirldDua delay(); updateTransactionCounters(); round.forEachEventTransaction((event, transaction) -> - handleConsensusTransaction(event, transaction, swirldDualState, round.getRoundNum())); + handleConsensusTransaction(event, transaction, platformState, round.getRoundNum())); } /** @@ -1089,12 +1089,12 @@ private void updateTransactionCounters() { private void handleConsensusTransaction( final ConsensusEvent event, final ConsensusTransaction trans, - final SwirldDualState dualState, + final PlatformState platformState, final long roundNum) { try { waitForSignatureValidation(trans); handleTransaction( - event.getCreatorId(), event.getTimeCreated(), trans.getConsensusTimestamp(), trans, dualState); + event.getCreatorId(), event.getTimeCreated(), trans.getConsensusTimestamp(), trans, platformState); } catch (final InterruptedException e) { logger.info( TESTING_EXCEPTIONS_ACCEPTABLE_RECONNECT.getMarker(), @@ -1123,7 +1123,7 @@ private void handleTransaction( @NonNull final Instant timeCreated, @NonNull final Instant timestamp, @NonNull final ConsensusTransaction trans, - @NonNull final SwirldDualState swirldDualState) { + @NonNull final PlatformState platformState) { if (getConfig().isAppendSig()) { try { final TestTransactionWrapper testTransactionWrapper = @@ -1211,7 +1211,7 @@ private void handleTransaction( handleControlTransaction(testTransaction.get(), id, timestamp); break; case FREEZETRANSACTION: - handleFreezeTransaction(testTransaction.get(), swirldDualState); + handleFreezeTransaction(testTransaction.get(), platformState); break; case SIMPLEACTION: handleSimpleAction(testTransaction.get().getSimpleAction()); @@ -1260,7 +1260,7 @@ private void genesisInit() { @Override public void init( final Platform platform, - final SwirldDualState swirldDualState, + final PlatformState platformState, final InitTrigger trigger, final SoftwareVersion previousSoftwareVersion) { @@ -1289,7 +1289,7 @@ public void init( initializeExpirationQueueAndAccountsSet(); logger.info(LOGM_DEMO_INFO, "Dual state received in init function {}", () -> new ApplicationDualStatePayload( - swirldDualState.getFreezeTime(), swirldDualState.getLastFrozenTime()) + platformState.getFreezeTime(), platformState.getLastFrozenTime()) .toString()); logger.info(LOGM_STARTUP, () -> new SoftwareVersionPayload( diff --git a/platform-sdk/platform-apps/tests/PlatformTestingTool/src/main/java/com/swirlds/demo/platform/freeze/FreezeTransactionHandler.java b/platform-sdk/platform-apps/tests/PlatformTestingTool/src/main/java/com/swirlds/demo/platform/freeze/FreezeTransactionHandler.java index 219da4ae3400..406becf566e7 100644 --- a/platform-sdk/platform-apps/tests/PlatformTestingTool/src/main/java/com/swirlds/demo/platform/freeze/FreezeTransactionHandler.java +++ b/platform-sdk/platform-apps/tests/PlatformTestingTool/src/main/java/com/swirlds/demo/platform/freeze/FreezeTransactionHandler.java @@ -17,7 +17,7 @@ package com.swirlds.demo.platform.freeze; import com.swirlds.demo.platform.fs.stresstest.proto.FreezeTransaction; -import com.swirlds.platform.system.SwirldDualState; +import com.swirlds.platform.state.PlatformState; import java.time.Instant; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -28,10 +28,10 @@ public class FreezeTransactionHandler { private static final Logger logger = LogManager.getLogger(FreezeTransactionHandler.class); private static final Marker LOGM_FREEZE = MarkerManager.getMarker("FREEZE"); - public static boolean freeze(final FreezeTransaction transaction, final SwirldDualState swirldDualState) { + public static boolean freeze(final FreezeTransaction transaction, final PlatformState platformState) { logger.debug(LOGM_FREEZE, "Handling FreezeTransaction: " + transaction); try { - swirldDualState.setFreezeTime(Instant.ofEpochSecond(transaction.getStartTimeEpochSecond())); + platformState.setFreezeTime(Instant.ofEpochSecond(transaction.getStartTimeEpochSecond())); return true; } catch (IllegalArgumentException ex) { logger.warn(LOGM_FREEZE, "FreezeTransactionHandler::freeze fails. {}", ex.getMessage()); diff --git a/platform-sdk/platform-apps/tests/PlatformTestingTool/src/test/java/com/swirlds/demo/merkle/map/MapValueFCQTests.java b/platform-sdk/platform-apps/tests/PlatformTestingTool/src/test/java/com/swirlds/demo/merkle/map/MapValueFCQTests.java index f05181e7235c..7e4a56ad1a00 100644 --- a/platform-sdk/platform-apps/tests/PlatformTestingTool/src/test/java/com/swirlds/demo/merkle/map/MapValueFCQTests.java +++ b/platform-sdk/platform-apps/tests/PlatformTestingTool/src/test/java/com/swirlds/demo/merkle/map/MapValueFCQTests.java @@ -39,7 +39,7 @@ import com.swirlds.merkle.map.test.lifecycle.ExpectedValue; import com.swirlds.merkle.map.test.pta.MapKey; import com.swirlds.merkle.map.test.pta.TransactionRecord; -import com.swirlds.platform.state.DualStateImpl; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.SoftwareVersion; @@ -87,7 +87,7 @@ public static void setUp() throws ConstructableRegistryException { AddressBook addressBook = Mockito.spy(AddressBook.class); when(addressBook.getNumberWithWeight()).thenReturn(4); when(platform.getAddressBook()).thenReturn(addressBook); - state.init(platform, new DualStateImpl(), InitTrigger.RESTART, SoftwareVersion.NO_VERSION); + state.init(platform, new PlatformState(), InitTrigger.RESTART, SoftwareVersion.NO_VERSION); state.initChildren(); } diff --git a/platform-sdk/platform-apps/tests/StatsSigningTestingTool/src/main/java/com/swirlds/demo/stats/signing/StatsSigningTestingToolState.java b/platform-sdk/platform-apps/tests/StatsSigningTestingTool/src/main/java/com/swirlds/demo/stats/signing/StatsSigningTestingToolState.java index fd4e3400a12d..c5aed3bb7173 100644 --- a/platform-sdk/platform-apps/tests/StatsSigningTestingTool/src/main/java/com/swirlds/demo/stats/signing/StatsSigningTestingToolState.java +++ b/platform-sdk/platform-apps/tests/StatsSigningTestingTool/src/main/java/com/swirlds/demo/stats/signing/StatsSigningTestingToolState.java @@ -37,8 +37,8 @@ import com.swirlds.common.io.streams.SerializableDataOutputStream; import com.swirlds.common.merkle.MerkleLeaf; import com.swirlds.common.merkle.impl.PartialMerkleLeaf; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.events.Event; import com.swirlds.platform.system.transaction.ConsensusTransaction; @@ -121,7 +121,7 @@ public void preHandle(final Event event) { * {@inheritDoc} */ @Override - public void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) { + public void handleConsensusRound(final Round round, final PlatformState platformState) { throwIfImmutable(); round.forEachTransaction(this::handleTransaction); } diff --git a/platform-sdk/platform-apps/tests/StressTestingTool/src/main/java/com/swirlds/demo/stress/StressTestingToolState.java b/platform-sdk/platform-apps/tests/StressTestingTool/src/main/java/com/swirlds/demo/stress/StressTestingToolState.java index e84371806813..6c6d0600ef02 100644 --- a/platform-sdk/platform-apps/tests/StressTestingTool/src/main/java/com/swirlds/demo/stress/StressTestingToolState.java +++ b/platform-sdk/platform-apps/tests/StressTestingTool/src/main/java/com/swirlds/demo/stress/StressTestingToolState.java @@ -31,11 +31,11 @@ import com.swirlds.common.merkle.MerkleLeaf; import com.swirlds.common.merkle.impl.PartialMerkleLeaf; import com.swirlds.common.utility.ByteUtils; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Platform; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.events.Event; import com.swirlds.platform.system.transaction.ConsensusTransaction; @@ -78,7 +78,7 @@ public synchronized StressTestingToolState copy() { public void init( @NonNull final Platform platform, - @NonNull final SwirldDualState swirldDualState, + @NonNull final PlatformState platformState, @NonNull final InitTrigger trigger, @NonNull final SoftwareVersion previousSoftwareVersion) { this.config = platform.getContext().getConfiguration().getConfigData(StressTestingToolConfig.class); @@ -96,7 +96,7 @@ public void preHandle(final Event event) { * {@inheritDoc} */ @Override - public void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) { + public void handleConsensusRound(final Round round, final PlatformState platformState) { throwIfImmutable(); round.forEachTransaction(this::handleTransaction); } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/ConsensusImpl.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/ConsensusImpl.java index bfad19a14daf..cead95025e11 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/ConsensusImpl.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/ConsensusImpl.java @@ -39,7 +39,6 @@ import com.swirlds.platform.internal.ConsensusRound; import com.swirlds.platform.internal.EventImpl; import com.swirlds.platform.metrics.ConsensusMetrics; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.signed.SignedState; import com.swirlds.platform.system.address.AddressBook; import edu.umd.cs.findbugs.annotations.NonNull; @@ -209,44 +208,7 @@ public ConsensusImpl( @Override public void loadFromSignedState(@NonNull final SignedState signedState) { reset(); - final PlatformData platformData = - signedState.getState().getPlatformState().getPlatformData(); - if (platformData.getEvents() != null) { - loadLegacyState(platformData); - } else { - loadSnapshot(platformData.getSnapshot()); - } - } - - private void loadLegacyState(@NonNull final PlatformData platformData) { - migrationMode = true; - - // create all the rounds that we have events for - rounds.loadFromMinGen(platformData.getMinGenInfo()); - updateRoundGenerations(rounds.getFameDecidedBelow()); - - for (final EventImpl event : platformData.getEvents()) { - event.setRoundCreated( - // this is where round created used to be stored, only needed for migration - event.getConsensusData().getRoundCreated()); - calculateMetadata(event); - event.setConsensus(true); - // events are stored in consensus order, so the last event in consensus order should be - // incremented by 1 to get the numConsensus - numConsensus = event.getConsensusOrder() + 1; - } - - // The lastConsensusTime is equal to the last transaction that has been handled - lastConsensusTime = platformData.getConsensusTimestamp(); - - logger.debug( - STARTUP.getMarker(), - "ConsensusImpl is initialized from signed state. minRound: {}(min gen = {})," - + " maxRound: {}(max gen = {})", - this::getMinRound, - this::getMinRoundGeneration, - this::getMaxRound, - this::getMaxRoundGeneration); + loadSnapshot(signedState.getState().getPlatformState().getSnapshot()); } /** diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/SwirldsPlatform.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/SwirldsPlatform.java index 9474a1fbf977..6536b33454a6 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/SwirldsPlatform.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/SwirldsPlatform.java @@ -82,7 +82,6 @@ import com.swirlds.platform.dispatch.triggers.flow.DiskStateLoadedTrigger; import com.swirlds.platform.dispatch.triggers.flow.ReconnectStateLoadedTrigger; import com.swirlds.platform.event.EventCounter; -import com.swirlds.platform.event.EventUtils; import com.swirlds.platform.event.GossipEvent; import com.swirlds.platform.event.creation.AsyncEventCreationManager; import com.swirlds.platform.event.creation.EventCreationManager; @@ -194,9 +193,7 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicLong; @@ -469,8 +466,7 @@ public class SwirldsPlatform implements Platform { if (emergencyRecoveryManager.getEmergencyRecoveryFile() != null) { epochHash = emergencyRecoveryManager.getEmergencyRecoveryFile().hash(); } else { - epochHash = - initialState.getState().getPlatformState().getPlatformData().getEpochHash(); + epochHash = initialState.getState().getPlatformState().getEpochHash(); } StartupStateUtils.doRecoveryCleanup( @@ -895,7 +891,7 @@ public class SwirldsPlatform implements Platform { initialMinimumGenerationNonAncient = 0; } else { initialMinimumGenerationNonAncient = - initialState.getState().getPlatformState().getPlatformData().getMinimumGenerationNonAncient(); + initialState.getState().getPlatformState().getMinimumGenerationNonAncient(); latestImmutableState.setState(initialState.reserve("set latest immutable to initial state")); stateManagementComponent.stateToLoad(initialState, SourceOfSignedState.DISK); savedStateController.registerSignedStateFromDisk(initialState); @@ -1001,8 +997,7 @@ private void initializeState(@NonNull final SignedState signedState) { previousSoftwareVersion = NO_VERSION; trigger = GENESIS; } else { - previousSoftwareVersion = - signedState.getState().getPlatformState().getPlatformData().getCreationSoftwareVersion(); + previousSoftwareVersion = signedState.getState().getPlatformState().getCreationSoftwareVersion(); trigger = RESTART; } @@ -1017,7 +1012,7 @@ private void initializeState(@NonNull final SignedState signedState) { throw new IllegalStateException("Expected initial swirld state to be unhashed"); } - initialState.getSwirldState().init(this, initialState.getSwirldDualState(), trigger, previousSoftwareVersion); + initialState.getSwirldState().init(this, initialState.getPlatformState(), trigger, previousSoftwareVersion); abortAndThrowIfInterrupted( () -> { @@ -1059,27 +1054,7 @@ private void loadStateIntoEventCreator(@NonNull final SignedState signedState) { try { eventCreator.setMinimumGenerationNonAncient( - signedState.getState().getPlatformState().getPlatformData().getMinimumGenerationNonAncient()); - - // newer states will not have events, so we need to check for null - if (signedState.getState().getPlatformState().getPlatformData().getEvents() == null) { - return; - } - - // The event creator may not be started yet. To avoid filling up queues, only register - // the latest event from each creator. These are the only ones the event creator cares about. - - final Map latestEvents = new HashMap<>(); - - for (final EventImpl event : - signedState.getState().getPlatformState().getPlatformData().getEvents()) { - latestEvents.put(event.getCreatorId(), event); - } - - for (final EventImpl event : latestEvents.values()) { - eventCreator.registerEvent(event); - } - + signedState.getState().getPlatformState().getMinimumGenerationNonAncient()); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted while loading state into event creator", e); @@ -1095,23 +1070,7 @@ private void loadStateIntoConsensus(@NonNull final SignedState signedState) { Objects.requireNonNull(signedState); consensusRef.get().loadFromSignedState(signedState); - - // old states will have events in them that need to be loaded, newer states will not - if (signedState.getEvents() != null) { - shadowGraph.initFromEvents( - EventUtils.prepareForShadowGraph( - // we need to pass in a copy of the array, otherwise prepareForShadowGraph will rearrange - // the events in the signed state which will cause issues for other components that depend - // on it - signedState.getEvents().clone()), - // we need to provide the minGen from consensus so that expiry matches after a restart/reconnect - consensusRef.get().getMinRoundGeneration()); - - // Intentionally don't bother initiating the latestEventTipsetTracker here. We don't support this - // code path way any more. - } else { - shadowGraph.startFromGeneration(consensusRef.get().getMinGenerationNonAncient()); - } + shadowGraph.startFromGeneration(consensusRef.get().getMinGenerationNonAncient()); gossip.loadFromSignedState(signedState); } @@ -1137,13 +1096,9 @@ private void loadReconnectState(final SignedState signedState) { .getSwirldState() .init( this, - signedState.getState().getSwirldDualState(), + signedState.getState().getPlatformState(), InitTrigger.RECONNECT, - signedState - .getState() - .getPlatformState() - .getPlatformData() - .getCreationSoftwareVersion()); + signedState.getState().getPlatformState().getCreationSoftwareVersion()); if (!Objects.equals(signedState.getState().getHash(), reconnectHash)) { throw new IllegalStateException( "State hash is not permitted to change during a reconnect init() call. Previous hash was " @@ -1206,11 +1161,8 @@ private void loadReconnectState(final SignedState signedState) { try { preconsensusEventWriter.registerDiscontinuity(signedState.getRound()); - preconsensusEventWriter.setMinimumGenerationNonAncient(signedState - .getState() - .getPlatformState() - .getPlatformData() - .getMinimumGenerationNonAncient()); + preconsensusEventWriter.setMinimumGenerationNonAncient( + signedState.getState().getPlatformState().getMinimumGenerationNonAncient()); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted while loading updating PCES after reconnect", e); diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/cli/GenesisPlatformStateCommand.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/cli/GenesisPlatformStateCommand.java index 28567778d6de..3faa7da6a915 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/cli/GenesisPlatformStateCommand.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/cli/GenesisPlatformStateCommand.java @@ -78,18 +78,8 @@ public Integer call() throws IOException, ExecutionException, InterruptedExcepti SignedStateFileReader.readStateFile(platformContext, statePath); try (final ReservedSignedState reservedSignedState = deserializedSignedState.reservedSignedState()) { System.out.printf("Replacing platform data %n"); - reservedSignedState - .get() - .getState() - .getPlatformState() - .getPlatformData() - .setRound(PlatformData.GENESIS_ROUND); - reservedSignedState - .get() - .getState() - .getPlatformState() - .getPlatformData() - .setSnapshot(SyntheticSnapshot.getGenesisSnapshot()); + reservedSignedState.get().getState().getPlatformState().setRound(PlatformData.GENESIS_ROUND); + reservedSignedState.get().getState().getPlatformState().setSnapshot(SyntheticSnapshot.getGenesisSnapshot()); System.out.printf("Hashing state %n"); MerkleCryptoFactory.getInstance() .digestTreeAsync(reservedSignedState.get().getState()) diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/components/appcomm/AppCommunicationComponent.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/components/appcomm/AppCommunicationComponent.java index 4f5b19b4960c..30ac6faacb5f 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/components/appcomm/AppCommunicationComponent.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/components/appcomm/AppCommunicationComponent.java @@ -125,7 +125,7 @@ public void newLatestCompleteStateEvent(@NonNull final SignedState signedState) private void latestCompleteStateHandler(@NonNull final ReservedSignedState reservedSignedState) { final NewSignedStateNotification notification = new NewSignedStateNotification( reservedSignedState.get().getSwirldState(), - reservedSignedState.get().getState().getSwirldDualState(), + reservedSignedState.get().getState().getPlatformState(), reservedSignedState.get().getRound(), reservedSignedState.get().getConsensusTimestamp()); diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/consensus/RoundCalculationUtils.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/consensus/RoundCalculationUtils.java index 722f8f841841..33692d78162f 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/consensus/RoundCalculationUtils.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/consensus/RoundCalculationUtils.java @@ -72,10 +72,9 @@ public static long getMinGenNonAncient( * @return minimum non-ancient generation */ public static long getMinGenNonAncient(final int roundsNonAncient, final SignedState signedState) { - return getMinGenNonAncient(roundsNonAncient, signedState.getRound(), round -> signedState - .getState() - .getPlatformState() - .getPlatformData() - .getMinGen(round)); + return getMinGenNonAncient( + roundsNonAncient, + signedState.getRound(), + round -> signedState.getState().getPlatformState().getMinGen(round)); } } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/eventhandling/ConsensusRoundHandler.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/eventhandling/ConsensusRoundHandler.java index 59aa2c1aa8fe..9e9c211978bd 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/eventhandling/ConsensusRoundHandler.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/eventhandling/ConsensusRoundHandler.java @@ -48,6 +48,7 @@ import com.swirlds.platform.internal.EventImpl; import com.swirlds.platform.metrics.ConsensusHandlingMetrics; import com.swirlds.platform.observers.ConsensusRoundObserver; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.State; import com.swirlds.platform.state.SwirldStateManager; import com.swirlds.platform.state.signed.ReservedSignedState; @@ -367,6 +368,7 @@ private void applyConsensusRoundToState(final ConsensusRound round) throws Inter consensusTimingStat.setTimePoint(1); propagateConsensusData(round); + updatePlatformState(round); if (round.getEventCount() > 0) { consensusHandlingMetrics.recordConsensusTime(round.getConsensusTimestamp()); @@ -399,8 +401,7 @@ private void applyConsensusRoundToState(final ConsensusRound round) throws Inter // . For an accurate stat on how much time it takes to create a signed state, refer to // newSignedStateCycleTiming in Statistics consensusTimingStat.setTimePoint(5); - - updatePlatformState(round); + updateRunningEventHash(); consensusTimingStat.setTimePoint(6); @@ -439,21 +440,29 @@ private boolean timeToSignState(final long roundNum) { } /** - * Populate the {@link com.swirlds.platform.state.PlatformState PlatformState} with all of its needed data. + * Populate the {@link com.swirlds.platform.state.PlatformState PlatformState} with all of its needed data for this + * round, with the exception of the running event hash. Wait until transactions are handled before updating this. + * This makes it less likely that we will have to wait for the hash to be computed. */ - private void updatePlatformState(final ConsensusRound round) throws InterruptedException { - final Hash runningHash = eventsConsRunningHash.getFutureHash().getAndRethrow(); + private void updatePlatformState(final ConsensusRound round) { + final PlatformState platformState = + swirldStateManager.getConsensusState().getPlatformState(); + + platformState.setRound(round.getRoundNum()); + platformState.setConsensusTimestamp(round.getConsensusTimestamp()); + platformState.setCreationSoftwareVersion(softwareVersion); + platformState.setRoundsNonAncient(roundsNonAncient); + platformState.setSnapshot(round.getSnapshot()); + } - swirldStateManager - .getConsensusState() - .getPlatformState() - .getPlatformData() - .setRound(round.getRoundNum()) - .setHashEventsCons(runningHash) - .setConsensusTimestamp(round.getConsensusTimestamp()) - .setCreationSoftwareVersion(softwareVersion) - .setRoundsNonAncient(roundsNonAncient) - .setSnapshot(round.getSnapshot()); + /** + * Update the running event hash in the platform state. + */ + private void updateRunningEventHash() throws InterruptedException { + final PlatformState platformState = + swirldStateManager.getConsensusState().getPlatformState(); + final Hash runningHash = eventsConsRunningHash.getFutureHash().getAndRethrow(); + platformState.setRunningEventHash(runningHash); } private void createSignedState() throws InterruptedException { diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/DefaultSignedStateValidator.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/DefaultSignedStateValidator.java index 4f144d2aa2bb..1991b12b14bf 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/DefaultSignedStateValidator.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/DefaultSignedStateValidator.java @@ -67,11 +67,10 @@ public void validate( private void throwIfOld(final SignedState signedState, final SignedStateValidationData previousStateData) throws SignedStateInvalidException { - if (signedState.getState().getPlatformState().getPlatformData().getRound() < previousStateData.round() + if (signedState.getState().getPlatformState().getRound() < previousStateData.round() || signedState .getState() .getPlatformState() - .getPlatformData() .getConsensusTimestamp() .isBefore(previousStateData.consensusTimestamp())) { logger.error( diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/ReconnectHelper.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/ReconnectHelper.java index e966c18d1ee9..b7bc25bf5af7 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/ReconnectHelper.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/ReconnectHelper.java @@ -24,7 +24,6 @@ import com.swirlds.logging.legacy.payload.ReconnectFinishPayload; import com.swirlds.logging.legacy.payload.ReconnectLoadFailurePayload; import com.swirlds.logging.legacy.payload.ReconnectStartPayload; -import com.swirlds.platform.event.EventUtils; import com.swirlds.platform.network.Connection; import com.swirlds.platform.state.State; import com.swirlds.platform.state.signed.ReservedSignedState; @@ -150,11 +149,6 @@ private ReservedSignedState reconnectLearner(final Connection conn, final Signed {}""", () -> reservedState.get().getState().getInfoString(stateConfig.debugHashDepth())); - logger.info( - RECONNECT.getMarker(), - "signed state events:\n{}", - () -> EventUtils.toShortStrings(reservedState.get().getEvents())); - return reservedState; } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/ReconnectLearner.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/ReconnectLearner.java index 4539c7d9b000..08681ba0d792 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/ReconnectLearner.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/ReconnectLearner.java @@ -103,8 +103,7 @@ public ReconnectLearner( this.statistics = Objects.requireNonNull(statistics); // Save some of the current state data for validation - this.stateValidationData = - new SignedStateValidationData(currentState.getPlatformState().getPlatformData(), addressBook); + this.stateValidationData = new SignedStateValidationData(currentState.getPlatformState(), addressBook); } /** diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/emergency/EmergencySignedStateValidator.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/emergency/EmergencySignedStateValidator.java index 48fbd854c285..b6c028dc9362 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/emergency/EmergencySignedStateValidator.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/reconnect/emergency/EmergencySignedStateValidator.java @@ -58,7 +58,7 @@ public EmergencySignedStateValidator( * {@inheritDoc} * * If the {@code reservedSignedState} is matches the request round and hash exactly, this method updates the next epoch hash - * via {@link com.swirlds.platform.state.PlatformData#setNextEpochHash(Hash)}. Doing so does not modify the hash, + * via {@link com.swirlds.platform.state.PlatformState#setNextEpochHash(Hash)}. Doing so does not modify the hash, * but will trigger the epoch hash to update when the next round reaches consensus. * Note: the previous state is ignored by this validator. Emergency round, emergency state hash, and epoch hash * are used instead. @@ -106,7 +106,7 @@ private void verifyStateHashMatches(final SignedState signedState) { // FUTURE WORK: move this to the calling code (saved state loading and emergency reconnect) when // reconnect is refactored such that it no longer needs to be called by sync - signedState.getState().getPlatformState().getPlatformData().setNextEpochHash(emergencyRecoveryFile.hash()); + signedState.getState().getPlatformState().setNextEpochHash(emergencyRecoveryFile.hash()); signedState.markAsRecoveryState(); logger.info( @@ -146,8 +146,7 @@ private void verifyLaterRoundIsValid(final SignedState signedState, final Addres } private void checkEpochHash(final SignedState signedState) { - final Hash epochHash = - signedState.getState().getPlatformState().getPlatformData().getEpochHash(); + final Hash epochHash = signedState.getState().getPlatformState().getEpochHash(); if (!emergencyRecoveryFile.hash().equals(epochHash)) { logger.error( EXCEPTION.getMarker(), diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/recovery/EventRecoveryWorkflow.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/recovery/EventRecoveryWorkflow.java index 8d8ac78d270c..288cd70e9a49 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/recovery/EventRecoveryWorkflow.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/recovery/EventRecoveryWorkflow.java @@ -47,6 +47,7 @@ import com.swirlds.platform.recovery.internal.EventStreamRoundIterator; import com.swirlds.platform.recovery.internal.RecoveredState; import com.swirlds.platform.recovery.internal.RecoveryPlatform; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.State; import com.swirlds.platform.state.signed.ReservedSignedState; import com.swirlds.platform.state.signed.SignedState; @@ -54,7 +55,6 @@ import com.swirlds.platform.state.signed.SignedStateFileWriter; import com.swirlds.platform.system.InitTrigger; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldMain; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.events.ConsensusEvent; @@ -65,7 +65,9 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; -import java.util.*; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; import java.util.concurrent.ExecutionException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -288,14 +290,9 @@ public static RecoveredState reapplyTransactions( .getSwirldState() .init( platform, - initialState.get().getState().getSwirldDualState(), + initialState.get().getState().getPlatformState(), InitTrigger.EVENT_STREAM_RECOVERY, - initialState - .get() - .getState() - .getPlatformState() - .getPlatformData() - .getCreationSoftwareVersion()); + initialState.get().getState().getPlatformState().getCreationSoftwareVersion()); appMain.init(platform, platform.getSelfId()); @@ -342,10 +339,10 @@ public static RecoveredState reapplyTransactions( /** * Apply a single round and generate a new state. The previous state is released. * - * @param platformContext the current context - * @param previousState the previous round's signed state - * @param round the next round - * @param config the consensus configuration + * @param platformContext the current context + * @param previousState the previous round's signed state + * @param round the next round + * @param config the consensus configuration * @return the resulting signed state */ private static ReservedSignedState handleNextRound( @@ -359,36 +356,34 @@ private static ReservedSignedState handleNextRound( final State newState = previousState.get().getState().copy(); final EventImpl lastEvent = (EventImpl) getLastEvent(round); CryptographyHolder.get().digestSync(lastEvent.getBaseEvent().getHashedData()); - newState.getPlatformState() - .getPlatformData() - .setRound(round.getRoundNum()) - .setHashEventsCons(getHashEventsCons(previousState.get().getHashEventsCons(), round)) - .setConsensusTimestamp(currentRoundTimestamp) - .setSnapshot(SyntheticSnapshot.generateSyntheticSnapshot( - round.getRoundNum(), - lastEvent.getConsensusOrder(), - currentRoundTimestamp, - config, - lastEvent.getBaseEvent())) - .setCreationSoftwareVersion(previousState - .get() - .getState() - .getPlatformState() - .getPlatformData() - .getCreationSoftwareVersion()); + + final PlatformState platformState = newState.getPlatformState(); + + platformState.setRound(round.getRoundNum()); + platformState.setRunningEventHash(getHashEventsCons(previousState.get().getHashEventsCons(), round)); + platformState.setConsensusTimestamp(currentRoundTimestamp); + platformState.setSnapshot(SyntheticSnapshot.generateSyntheticSnapshot( + round.getRoundNum(), + lastEvent.getConsensusOrder(), + currentRoundTimestamp, + config, + lastEvent.getBaseEvent())); + platformState.setCreationSoftwareVersion( + previousState.get().getState().getPlatformState().getCreationSoftwareVersion()); applyTransactions( previousState.get().getSwirldState().cast(), newState.getSwirldState().cast(), - newState.getSwirldDualState(), + newState.getPlatformState(), round); final boolean isFreezeState = isFreezeState( previousState.get().getConsensusTimestamp(), currentRoundTimestamp, - newState.getPlatformDualState().getFreezeTime()); + newState.getPlatformState().getFreezeTime()); if (isFreezeState) { - newState.getPlatformDualState().setLastFrozenTimeToBeCurrentFreezeTime(); + newState.getPlatformState() + .setLastFrozenTime(newState.getPlatformState().getFreezeTime()); } final ReservedSignedState signedState = new SignedState( @@ -449,13 +444,13 @@ static ConsensusEvent getLastEvent(final Round round) { * * @param immutableState the immutable swirld state for the previous round * @param mutableState the swirld state for the current round - * @param dualState the dual state for the current round + * @param platformState the platform state for the current round * @param round the current round */ static void applyTransactions( final SwirldState immutableState, final SwirldState mutableState, - final SwirldDualState dualState, + final PlatformState platformState, final Round round) { mutableState.throwIfImmutable(); @@ -464,7 +459,7 @@ static void applyTransactions( immutableState.preHandle(event); } - mutableState.handleConsensusRound(round, dualState); + mutableState.handleConsensusRound(round, platformState); // FUTURE WORK: there are currently no system transactions that are capable of modifying // the state. If/when system transactions capable of modifying state are added, this workflow diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/DualStateImpl.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/DualStateImpl.java index d7c1435a899e..e9915d9be87d 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/DualStateImpl.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/DualStateImpl.java @@ -16,30 +16,23 @@ package com.swirlds.platform.state; -import static com.swirlds.logging.legacy.LogMarker.FREEZE; - -import com.swirlds.base.utility.ToStringBuilder; import com.swirlds.common.io.streams.SerializableDataInputStream; import com.swirlds.common.io.streams.SerializableDataOutputStream; import com.swirlds.common.merkle.MerkleLeaf; import com.swirlds.common.merkle.impl.PartialMerkleLeaf; -import com.swirlds.logging.legacy.payload.SetFreezeTimePayload; -import com.swirlds.logging.legacy.payload.SetLastFrozenTimePayload; -import com.swirlds.platform.system.SwirldDualState; -import com.swirlds.platform.system.UptimeData; -import com.swirlds.platform.uptime.MutableUptimeData; import com.swirlds.platform.uptime.UptimeDataImpl; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.IOException; import java.time.Instant; -import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Contains any data that is either read or written by the platform and the application + * @deprecated can be removed after we don't need it for migration */ -public class DualStateImpl extends PartialMerkleLeaf implements PlatformDualState, SwirldDualState, MerkleLeaf { +@Deprecated(forRemoval = true) +public class DualStateImpl extends PartialMerkleLeaf implements MerkleLeaf { private static final Logger logger = LogManager.getLogger(DualStateImpl.class); public static final long CLASS_ID = 0x565e2e04ce3782b8L; @@ -96,59 +89,23 @@ public void deserialize(SerializableDataInputStream in, int version) throws IOEx } /** - * {@inheritDoc} - */ - @NonNull - @Override - public UptimeData getUptimeData() { - return uptimeData; - } - - /** - * {@inheritDoc} + * Get the node uptime data. */ @NonNull - @Override - public MutableUptimeData getMutableUptimeData() { + public UptimeDataImpl getUptimeData() { return uptimeData; } /** - * {@inheritDoc} - */ - @Override - public void setFreezeTime(Instant freezeTime) { - this.freezeTime = freezeTime; - logger.info(FREEZE.getMarker(), "setFreezeTime: {}", () -> freezeTime); - logger.info(FREEZE.getMarker(), () -> new SetFreezeTimePayload(freezeTime).toString()); - } - - /** - * {@inheritDoc} + * Get the freeze time. */ - @Override public Instant getFreezeTime() { return freezeTime; } - protected void setLastFrozenTime(Instant lastFrozenTime) { - this.lastFrozenTime = lastFrozenTime; - } - /** - * {@inheritDoc} - */ - @Override - public void setLastFrozenTimeToBeCurrentFreezeTime() { - this.lastFrozenTime = freezeTime; - logger.info(FREEZE.getMarker(), "setLastFrozenTimeToBeCurrentFreezeTime: {}", () -> lastFrozenTime); - logger.info(FREEZE.getMarker(), () -> new SetLastFrozenTimePayload(freezeTime).toString()); - } - - /** - * {@inheritDoc} + * Get the last frozen time. */ - @Override public Instant getLastFrozenTime() { return lastFrozenTime; } @@ -176,56 +133,4 @@ public int getVersion() { public DualStateImpl copy() { return new DualStateImpl(this); } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(final Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - final DualStateImpl dualState = (DualStateImpl) other; - return Objects.equals(freezeTime, dualState.freezeTime) - && Objects.equals(lastFrozenTime, dualState.lastFrozenTime); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return Objects.hash(freezeTime, lastFrozenTime); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return new ToStringBuilder(this) - .append("freezeTime", freezeTime) - .append("lastFrozenTime", lastFrozenTime) - .toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isInFreezePeriod(Instant consensusTime) { - // if freezeTime is not set, or consensusTime is before freezeTime, we are not in a freeze period - // if lastFrozenTime is equal to or after freezeTime, which means the nodes have been frozen once at/after the - // freezeTime, we are not in a freeze period - if (freezeTime == null || consensusTime.isBefore(freezeTime)) { - return false; - } - // Now we should check whether the nodes have been frozen at the freezeTime. - // when consensusTime is equal to or after freezeTime, - // and lastFrozenTime is before freezeTime, we are in a freeze period. - return lastFrozenTime == null || lastFrozenTime.isBefore(freezeTime); - } } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/GenesisStateBuilder.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/GenesisStateBuilder.java index 2c2d8360577d..4df610752b6a 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/GenesisStateBuilder.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/GenesisStateBuilder.java @@ -42,36 +42,17 @@ private static PlatformState buildGenesisPlatformState( final AddressBook addressBook, final SoftwareVersion appVersion) { final PlatformState platformState = new PlatformState(); - final PlatformData platformData = new PlatformData(); - platformState.setPlatformData(platformData); platformState.setAddressBook(addressBook.copy()); - platformData.setCreationSoftwareVersion(appVersion); - platformData.setRound(0); - platformData.setHashEventsCons(null); - platformData.setEpochHash(null); - platformData.setConsensusTimestamp(Instant.ofEpochSecond(0L)); + platformState.setCreationSoftwareVersion(appVersion); + platformState.setRound(0); + platformState.setRunningEventHash(null); + platformState.setEpochHash(null); + platformState.setConsensusTimestamp(Instant.ofEpochSecond(0L)); return platformState; } - /** - * Construct a genesis dual state. - * - * @param configuration configuration for the platform - * @return a genesis dual state - */ - private static DualStateImpl buildGenesisDualState(final BasicConfig configuration) { - final DualStateImpl dualState = new DualStateImpl(); - - final long genesisFreezeTime = configuration.genesisFreezeTime(); - if (genesisFreezeTime > 0) { - dualState.setFreezeTime(Instant.ofEpochSecond(genesisFreezeTime)); - } - - return dualState; - } - /** * Build and initialize a genesis state. * @@ -91,7 +72,11 @@ public static ReservedSignedState buildGenesisState( final State state = new State(); state.setPlatformState(buildGenesisPlatformState(addressBook, appVersion)); state.setSwirldState(swirldState); - state.setDualState(buildGenesisDualState(basicConfig)); + + final long genesisFreezeTime = basicConfig.genesisFreezeTime(); + if (genesisFreezeTime > 0) { + state.getPlatformState().setFreezeTime(Instant.ofEpochSecond(genesisFreezeTime)); + } final SignedState signedState = new SignedState(platformContext, state, "genesis state", false); return signedState.reserve("initial reservation on genesis state"); diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/LegacyPlatformState.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/LegacyPlatformState.java new file mode 100644 index 000000000000..19226f4b66b0 --- /dev/null +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/LegacyPlatformState.java @@ -0,0 +1,137 @@ +/* + * Copyright (C) 2016-2023 Hedera Hashgraph, LLC + * + * 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. + */ + +package com.swirlds.platform.state; + +import com.swirlds.common.merkle.MerkleInternal; +import com.swirlds.common.merkle.impl.PartialNaryMerkleInternal; +import com.swirlds.platform.system.address.AddressBook; + +/** + * This subtree contains state data which is managed and used exclusively by the platform. + * + * @deprecated This class is deprecated and will be removed in a future release. Use {@link PlatformState} instead. + */ +@Deprecated(forRemoval = true) +public class LegacyPlatformState extends PartialNaryMerkleInternal implements MerkleInternal { + + public static final long CLASS_ID = 0x483ae5404ad0d0bfL; + + private static final class ClassVersion { + public static final int ORIGINAL = 1; + public static final int ADDED_PREVIOUS_ADDRESS_BOOK = 2; + } + + private static final class ChildIndices { + public static final int PLATFORM_DATA = 0; + public static final int ADDRESS_BOOK = 1; + public static final int PREVIOUS_ADDRESS_BOOK = 2; + } + + public LegacyPlatformState() {} + + /** + * Copy constructor. + * + * @param that the node to copy + */ + private LegacyPlatformState(final LegacyPlatformState that) { + super(that); + if (that.getPlatformData() != null) { + this.setPlatformData(that.getPlatformData().copy()); + } + if (that.getAddressBook() != null) { + this.setAddressBook(that.getAddressBook().copy()); + } + if (that.getPreviousAddressBook() != null) { + this.setPreviousAddressBook(that.getPreviousAddressBook().copy()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getClassId() { + return CLASS_ID; + } + + /** + * {@inheritDoc} + */ + @Override + public int getVersion() { + return ClassVersion.ADDED_PREVIOUS_ADDRESS_BOOK; + } + + /** + * {@inheritDoc} + */ + @Override + public LegacyPlatformState copy() { + return new LegacyPlatformState(this); + } + + /** + * Get the address book. + */ + public AddressBook getAddressBook() { + return getChild(ChildIndices.ADDRESS_BOOK); + } + + /** + * Set the address book. + * + * @param addressBook an address book + */ + public void setAddressBook(final AddressBook addressBook) { + setChild(ChildIndices.ADDRESS_BOOK, addressBook); + } + + /** + * Get the object containing miscellaneous round information. + * + * @return round data + */ + public PlatformData getPlatformData() { + return getChild(ChildIndices.PLATFORM_DATA); + } + + /** + * Set the object containing miscellaneous platform information. + * + * @param round round data + */ + public void setPlatformData(final PlatformData round) { + setChild(ChildIndices.PLATFORM_DATA, round); + } + + /** + * Get the previous address book. + */ + public AddressBook getPreviousAddressBook() { + return getChild(ChildIndices.PREVIOUS_ADDRESS_BOOK); + } + + /** + * Set the previous address book. + * + * @param addressBook an address book + */ + public void setPreviousAddressBook(final AddressBook addressBook) { + setChild(ChildIndices.PREVIOUS_ADDRESS_BOOK, addressBook); + } +} diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformData.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformData.java index 80cfbb05cf6a..2967f06e613e 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformData.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformData.java @@ -40,7 +40,10 @@ /** * A collection of miscellaneous platform data. + * + * @deprecated this class is no longer used and is kept for migration purposes only */ +@Deprecated(forRemoval = true) public class PlatformData extends PartialMerkleLeaf implements MerkleLeaf { private static final long CLASS_ID = 0x1f89d0c43a8c08bdL; @@ -54,20 +57,19 @@ private static final class ClassVersion { public static final int EPOCH_HASH = 2; public static final int ROUNDS_NON_ANCIENT = 3; /** - * - Events are no longer serialized, the field is kept for migration purposes - * - Mingen is no longer stored directly, its part of the snapshot - * - restart/reconnect now uses a snapshot - * - lastTransactionTimestamp is no longer stored directly, its part of the snapshot - * - numEventsCons is no longer stored directly, its part of the snapshot - * */ + * - Events are no longer serialized, the field is kept for migration purposes - Mingen is no longer stored + * directly, its part of the snapshot - restart/reconnect now uses a snapshot - lastTransactionTimestamp is no + * longer stored directly, its part of the snapshot - numEventsCons is no longer stored directly, its part of + * the snapshot + */ public static final int CONSENSUS_SNAPSHOT = 4; } /** * The round of this state. This state represents the handling of all transactions that have reached consensus in * all previous rounds. All transactions from this round will eventually be applied to this state. The first state - * (genesis state) has a round of 0 because the first round is defined as round 1, and the genesis state is - * before any transactions are handled. + * (genesis state) has a round of 0 because the first round is defined as round 1, and the genesis state is before + * any transactions are handled. */ private long round = GENESIS_ROUND; diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformDualState.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformDualState.java deleted file mode 100644 index 052aea749a83..000000000000 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformDualState.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2016-2023 Hedera Hashgraph, LLC - * - * 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. - */ - -package com.swirlds.platform.state; - -import com.swirlds.platform.FreezePeriodChecker; -import com.swirlds.platform.system.DualState; -import com.swirlds.platform.uptime.MutableUptimeData; -import edu.umd.cs.findbugs.annotations.NonNull; - -/** - * Contains any data that is either read or written by the platform and the application, and contains methods available - * to the platform - */ -public interface PlatformDualState extends DualState, FreezePeriodChecker { - - /** - * Sets the lastFrozenTime to be current freezeTime - */ - void setLastFrozenTimeToBeCurrentFreezeTime(); - - /** - * Get the node uptime data. - */ - @NonNull - MutableUptimeData getMutableUptimeData(); -} diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformState.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformState.java index 86292ab7bd82..d504eb6d4734 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformState.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/PlatformState.java @@ -16,46 +16,147 @@ package com.swirlds.platform.state; -import com.swirlds.common.merkle.MerkleInternal; -import com.swirlds.common.merkle.impl.PartialNaryMerkleInternal; +import com.swirlds.common.crypto.Hash; +import com.swirlds.common.io.streams.SerializableDataInputStream; +import com.swirlds.common.io.streams.SerializableDataOutputStream; +import com.swirlds.common.merkle.MerkleLeaf; +import com.swirlds.common.merkle.impl.PartialMerkleLeaf; +import com.swirlds.platform.consensus.ConsensusSnapshot; +import com.swirlds.platform.consensus.RoundCalculationUtils; +import com.swirlds.platform.system.SoftwareVersion; import com.swirlds.platform.system.address.AddressBook; +import com.swirlds.platform.uptime.UptimeDataImpl; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Objects; /** - * This subtree contains state data which is managed and used exclusively by the platform. + * State managed and used by the platform. */ -public class PlatformState extends PartialNaryMerkleInternal implements MerkleInternal { +public class PlatformState extends PartialMerkleLeaf implements MerkleLeaf { - public static final long CLASS_ID = 0x483ae5404ad0d0bfL; + public static final long CLASS_ID = 0x52cef730a11cb6dfL; + + /** + * The round of the genesis state. + */ + public static final long GENESIS_ROUND = 0; private static final class ClassVersion { public static final int ORIGINAL = 1; - public static final int ADDED_PREVIOUS_ADDRESS_BOOK = 2; } - private static final class ChildIndices { - public static final int PLATFORM_DATA = 0; - public static final int ADDRESS_BOOK = 1; - public static final int PREVIOUS_ADDRESS_BOOK = 2; - } + /** + * The address book for this round. + */ + private AddressBook addressBook; + + /** + * The previous address book. A temporary workaround until dynamic address books are supported. + */ + private AddressBook previousAddressBook; + + /** + * The round of this state. This state represents the handling of all transactions that have reached consensus in + * all previous rounds. All transactions from this round will eventually be applied to this state. The first state + * (genesis state) has a round of 0 because the first round is defined as round 1, and the genesis state is before + * any transactions are handled. + */ + private long round = GENESIS_ROUND; + + /** + * The running hash of the hashes of all events have reached consensus up through the round that this SignedState + * represents. + */ + private Hash runningEventHash; + + /** + * the consensus timestamp for this signed state + */ + private Instant consensusTimestamp; + + /** + * The version of the application software that was responsible for creating this state. + */ + private SoftwareVersion creationSoftwareVersion; + + /** + * The epoch hash of this state. Updated every time emergency recovery is performed. + */ + private Hash epochHash; + + /** + * The next epoch hash, used to update the epoch hash at the next round boundary. This field is not part of the hash + * and is not serialized. + */ + private Hash nextEpochHash; + + /** + * The number of non-ancient rounds. + */ + private int roundsNonAncient; + + /** + * A snapshot of the consensus state at the end of the round, used for restart/reconnect + */ + private ConsensusSnapshot snapshot; + + /** + * the time when the freeze starts + */ + private Instant freezeTime; + + /** + * the last time when a freeze was performed + */ + private Instant lastFrozenTime; + + /** + * Data on node uptime. + */ + private UptimeDataImpl uptimeData = new UptimeDataImpl(); public PlatformState() {} /** * Copy constructor. * - * @param that - * the node to copy + * @param that the object to copy */ private PlatformState(final PlatformState that) { super(that); - if (that.getPlatformData() != null) { - this.setPlatformData(that.getPlatformData().copy()); - } - if (that.getAddressBook() != null) { - this.setAddressBook(that.getAddressBook().copy()); - } - if (that.getPreviousAddressBook() != null) { - this.setPreviousAddressBook(that.getPreviousAddressBook().copy()); + this.addressBook = that.addressBook.copy(); + this.previousAddressBook = that.previousAddressBook == null ? null : that.previousAddressBook.copy(); + this.round = that.round; + this.runningEventHash = that.runningEventHash; + this.consensusTimestamp = that.consensusTimestamp; + this.creationSoftwareVersion = that.creationSoftwareVersion; + this.epochHash = that.epochHash; + this.nextEpochHash = that.nextEpochHash; + this.roundsNonAncient = that.roundsNonAncient; + this.snapshot = that.snapshot; + this.freezeTime = that.freezeTime; + this.lastFrozenTime = that.lastFrozenTime; + this.uptimeData = that.uptimeData.copy(); + } + + /** + * Update the epoch hash if the next epoch hash is non-null and different from the current epoch hash. + */ + public void updateEpochHash() { + throwIfImmutable(); + if (nextEpochHash != null && !nextEpochHash.equals(epochHash)) { + // This is the first round after an emergency recovery round + // Set the epoch hash to the next value + epochHash = nextEpochHash; + + // set this to null so the value is consistent with a + // state loaded from disk or received via reconnect + nextEpochHash = null; } } @@ -67,12 +168,50 @@ public long getClassId() { return CLASS_ID; } + /** + * {@inheritDoc} + */ + @Override + public void serialize(final SerializableDataOutputStream out) throws IOException { + out.writeSerializable(addressBook, false); + out.writeSerializable(previousAddressBook, true); + out.writeLong(round); + out.writeSerializable(runningEventHash, false); + out.writeInstant(consensusTimestamp); + out.writeSerializable(creationSoftwareVersion, true); + out.writeSerializable(epochHash, false); + out.writeInt(roundsNonAncient); + out.writeSerializable(snapshot, false); + out.writeInstant(freezeTime); + out.writeInstant(lastFrozenTime); + out.writeSerializable(uptimeData, false); + } + + /** + * {@inheritDoc} + */ + @Override + public void deserialize(final SerializableDataInputStream in, final int version) throws IOException { + addressBook = in.readSerializable(false, AddressBook::new); + previousAddressBook = in.readSerializable(true, AddressBook::new); + round = in.readLong(); + runningEventHash = in.readSerializable(false, Hash::new); + consensusTimestamp = in.readInstant(); + creationSoftwareVersion = in.readSerializable(); + epochHash = in.readSerializable(false, Hash::new); + roundsNonAncient = in.readInt(); + snapshot = in.readSerializable(false, ConsensusSnapshot::new); + freezeTime = in.readInstant(); + lastFrozenTime = in.readInstant(); + uptimeData = in.readSerializable(false, UptimeDataImpl::new); + } + /** * {@inheritDoc} */ @Override public int getVersion() { - return ClassVersion.ADDED_PREVIOUS_ADDRESS_BOOK; + return ClassVersion.ORIGINAL; } /** @@ -83,56 +222,303 @@ public PlatformState copy() { return new PlatformState(this); } + /** + * Get the software version of the application that created this state. + * + * @return the creation version + */ + @Nullable + public SoftwareVersion getCreationSoftwareVersion() { + return creationSoftwareVersion; + } + + /** + * Set the software version of the application that created this state. + * + * @param creationVersion the creation version + */ + public void setCreationSoftwareVersion(@NonNull final SoftwareVersion creationVersion) { + this.creationSoftwareVersion = Objects.requireNonNull(creationVersion); + } + /** * Get the address book. */ + @Nullable public AddressBook getAddressBook() { - return getChild(ChildIndices.ADDRESS_BOOK); + return addressBook; } /** * Set the address book. * - * @param addressBook - * an address book + * @param addressBook an address book + */ + public void setAddressBook(@NonNull final AddressBook addressBook) { + this.addressBook = Objects.requireNonNull(addressBook); + } + + /** + * Get the previous address book. + */ + @Nullable + public AddressBook getPreviousAddressBook() { + return previousAddressBook; + } + + /** + * Set the previous address book. + * + * @param addressBook an address book */ - public void setAddressBook(final AddressBook addressBook) { - setChild(ChildIndices.ADDRESS_BOOK, addressBook); + public void setPreviousAddressBook(@Nullable final AddressBook addressBook) { + this.previousAddressBook = addressBook; } /** - * Get the object containing miscellaneous round information. + * Get the round when this state was generated. * - * @return round data + * @return a round number */ - public PlatformData getPlatformData() { - return getChild(ChildIndices.PLATFORM_DATA); + public long getRound() { + return round; } /** - * Set the object containing miscellaneous platform information. + * Set the round when this state was generated. * - * @param round - * round data + * @param round a round number */ - public void setPlatformData(final PlatformData round) { - setChild(ChildIndices.PLATFORM_DATA, round); + public void setRound(final long round) { + this.round = round; } /** - * Get the previous address book. + * Get the running hash of all events that have been applied to this state since the beginning of time. + * + * @return a running hash of events */ - public AddressBook getPreviousAddressBook() { - return getChild(ChildIndices.PREVIOUS_ADDRESS_BOOK); + @Nullable + public Hash getRunningEventHash() { + return runningEventHash; } /** - * Set the previous address book. + * Set the running hash of all events that have been applied to this state since the beginning of time. + * + * @param runningEventHash a running hash of events + */ + public void setRunningEventHash(@Nullable final Hash runningEventHash) { + this.runningEventHash = runningEventHash; + } + + /** + * Get the consensus timestamp for this state, defined as the timestamp of the first transaction that was applied in + * the round that created the state. + * + * @return a consensus timestamp + */ + @Nullable + public Instant getConsensusTimestamp() { + return consensusTimestamp; + } + + /** + * Set the consensus timestamp for this state, defined as the timestamp of the first transaction that was applied in + * the round that created the state. + * + * @param consensusTimestamp a consensus timestamp + */ + public void setConsensusTimestamp(@NonNull final Instant consensusTimestamp) { + this.consensusTimestamp = Objects.requireNonNull(consensusTimestamp); + } + + /** + * Get the minimum event generation for each node within this state. + * + * @return minimum generation info list, or null if this is a genesis state + */ + @Nullable + public List getMinGenInfo() { + return snapshot == null ? null : snapshot.minGens(); + } + + /** + * The minimum generation of famous witnesses for the round specified. This method only looks at non-ancient rounds + * contained within this state. + * + * @param round the round whose minimum generation will be returned + * @return the minimum generation for the round specified + * @throws NoSuchElementException if the generation information for this round is not contained withing this state + */ + public long getMinGen(final long round) { + final List minGenInfo = getMinGenInfo(); + if (minGenInfo == null) { + throw new IllegalStateException("No MinGen info found in state for round " + round); + } + + for (final MinGenInfo info : minGenInfo) { + if (info.round() == round) { + return info.minimumGeneration(); + } + } + throw new NoSuchElementException("No minimum generation found for round: " + round); + } + + /** + * Return the round generation of the oldest round in this state + * + * @return the generation of the oldest round + */ + public long getMinRoundGeneration() { + + final List minGenInfo = getMinGenInfo(); + if (minGenInfo == null) { + throw new IllegalStateException("No MinGen info found in state for round " + round); + } + + return getMinGenInfo().stream() + .findFirst() + .orElseThrow(() -> new IllegalStateException("No MinGen info found in state")) + .minimumGeneration(); + } + + /** + * Sets the epoch hash of this state. + * + * @param epochHash the epoch hash of this state + */ + public void setEpochHash(@Nullable final Hash epochHash) { + this.epochHash = epochHash; + } + + /** + * Gets the epoch hash of this state. + * + * @return the epoch hash of this state + */ + @Nullable + public Hash getEpochHash() { + return epochHash; + } + + /** + * Sets the next epoch hash of this state. + * + * @param nextEpochHash the next epoch hash of this state + */ + public void setNextEpochHash(@Nullable final Hash nextEpochHash) { + this.nextEpochHash = nextEpochHash; + } + + /** + * Gets the next epoch hash of this state. + * + * @return the next epoch hash of this state + */ + @Nullable + public Hash getNextEpochHash() { + return nextEpochHash; + } + + /** + * Sets the number of non-ancient rounds. + * + * @param roundsNonAncient the number of non-ancient rounds + */ + public void setRoundsNonAncient(final int roundsNonAncient) { + this.roundsNonAncient = roundsNonAncient; + } + + /** + * Gets the number of non-ancient rounds. + * + * @return the number of non-ancient rounds + */ + public int getRoundsNonAncient() { + return roundsNonAncient; + } + + /** + * Gets the minimum generation of non-ancient events. + * + * @return the minimum generation of non-ancient events + */ + public long getMinimumGenerationNonAncient() { + return RoundCalculationUtils.getMinGenNonAncient(roundsNonAncient, round, this::getMinGen); + } + + /** + * @return the consensus snapshot for this round + */ + @Nullable + public ConsensusSnapshot getSnapshot() { + return snapshot; + } + + /** + * @param snapshot the consensus snapshot for this round + */ + public void setSnapshot(@NonNull final ConsensusSnapshot snapshot) { + this.snapshot = Objects.requireNonNull(snapshot); + } + + /** + * Gets the time when the next freeze is scheduled to start. If null then there is no freeze scheduled. + * + * @return the time when the freeze starts + */ + @Nullable + public Instant getFreezeTime() { + return freezeTime; + } + + /** + * Sets the instant after which the platform will enter FREEZING status. When consensus timestamp of a signed state + * is after this instant, the platform will stop creating events and accepting transactions. This is used to safely + * shut down the platform for maintenance. + * + * @param freezeTime an Instant in UTC + */ + public void setFreezeTime(@Nullable final Instant freezeTime) { + this.freezeTime = freezeTime; + } + + /** + * Gets the last freezeTime based on which the nodes were frozen. If null then there has never been a freeze. + * + * @return the last freezeTime based on which the nodes were frozen + */ + @Nullable + public Instant getLastFrozenTime() { + return lastFrozenTime; + } + + /** + * Sets the last freezeTime based on which the nodes were frozen. + * + * @param lastFrozenTime the last freezeTime based on which the nodes were frozen + */ + public void setLastFrozenTime(@Nullable final Instant lastFrozenTime) { + this.lastFrozenTime = lastFrozenTime; + } + + /** + * Gets the uptime data. + * + * @return the uptime data + */ + @Nullable + public UptimeDataImpl getUptimeData() { + return uptimeData; + } + + /** + * Sets the uptime data. * - * @param addressBook - * an address book + * @param uptimeData the uptime data */ - public void setPreviousAddressBook(final AddressBook addressBook) { - setChild(ChildIndices.PREVIOUS_ADDRESS_BOOK, addressBook); + public void setUptimeData(@NonNull final UptimeDataImpl uptimeData) { + this.uptimeData = Objects.requireNonNull(uptimeData); } } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/State.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/State.java index 9dab8eae7b1f..5d0cd187b477 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/State.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/State.java @@ -16,30 +16,34 @@ package com.swirlds.platform.state; +import static com.swirlds.logging.legacy.LogMarker.STARTUP; + import com.swirlds.base.utility.ToStringBuilder; import com.swirlds.common.crypto.Hash; import com.swirlds.common.formatting.TextTable; import com.swirlds.common.merkle.MerkleInternal; -import com.swirlds.common.merkle.exceptions.IllegalChildIndexException; +import com.swirlds.common.merkle.MerkleNode; import com.swirlds.common.merkle.impl.PartialNaryMerkleInternal; import com.swirlds.common.merkle.utility.MerkleTreeVisualizer; import com.swirlds.common.utility.RuntimeObjectRecord; import com.swirlds.common.utility.RuntimeObjectRegistry; import com.swirlds.platform.consensus.ConsensusSnapshot; import com.swirlds.platform.internal.EventImpl; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Objects; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** - * The root of the merkle tree holding the state of the Swirlds ledger. Contains three children: the state used by the - * application; the state used by the platform; and the state used by both application and platform. + * The root of the merkle tree holding the state of the Swirlds ledger. Contains two children: the state used by the + * application and the state used by the platform. */ public class State extends PartialNaryMerkleInternal implements MerkleInternal { + private static final Logger logger = LogManager.getLogger(State.class); + private static final long CLASS_ID = 0x2971b4ba7dd84402L; private static class ClassVersion { @@ -48,6 +52,7 @@ private static class ClassVersion { public static final int EVENT_REFACTOR = 3; public static final int MIGRATE_TO_SERIALIZABLE = 4; public static final int ADD_DUAL_STATE = 5; + public static final int REMOVE_DUAL_STATE = 6; } private static class ChildIndices { @@ -61,7 +66,7 @@ private static class ChildIndices { */ public static final int PLATFORM_STATE = 1; /** - * The state either read or written by the platform and the application + * Not used after migration. */ public static final int DUAL_STATE = 2; } @@ -86,26 +91,48 @@ private State(final State that) { if (that.getPlatformState() != null) { this.setPlatformState(that.getPlatformState().copy()); } - if (that.getDualState() != null) { - this.setDualState(that.getDualState().copy()); - } } /** * {@inheritDoc} */ @Override - public boolean childHasExpectedType(final int index, final long childClassId) { - switch (index) { - case ChildIndices.SWIRLD_STATE: - return true; - case ChildIndices.PLATFORM_STATE: - return childClassId == PlatformState.CLASS_ID; - case ChildIndices.DUAL_STATE: - return childClassId == DualStateImpl.CLASS_ID; - default: - throw new IllegalChildIndexException(getMinimumChildCount(), getMaximumChildCount(), index); + public MerkleNode migrate(final int version) { + if (version < ClassVersion.REMOVE_DUAL_STATE) { + logger.info( + STARTUP.getMarker(), + "Migrating legacy platform state to new platform state at version (State version {} -> {}).", + version, + getVersion()); + + final State newState = new State(); + + final PlatformState newPlatformState = new PlatformState(); + + final LegacyPlatformState platformState = getChild(ChildIndices.PLATFORM_STATE); + final PlatformData platformData = platformState.getPlatformData(); + final DualStateImpl dualState = getChild(ChildIndices.DUAL_STATE); + + newPlatformState.setAddressBook(platformState.getAddressBook()); + newPlatformState.setPreviousAddressBook(platformState.getPreviousAddressBook()); + newPlatformState.setRound(platformData.getRound()); + newPlatformState.setRunningEventHash(platformData.getHashEventsCons()); + newPlatformState.setConsensusTimestamp(platformData.getConsensusTimestamp()); + newPlatformState.setCreationSoftwareVersion(platformData.getCreationSoftwareVersion()); + newPlatformState.setEpochHash(platformData.getEpochHash()); + newPlatformState.setNextEpochHash(platformData.getNextEpochHash()); + newPlatformState.setRoundsNonAncient(platformData.getRoundsNonAncient()); + newPlatformState.setSnapshot(platformData.getSnapshot()); + newPlatformState.setFreezeTime(dualState.getFreezeTime()); + newPlatformState.setLastFrozenTime(dualState.getLastFrozenTime()); + newPlatformState.setUptimeData(dualState.getUptimeData()); + + newState.setPlatformState(newPlatformState); + newState.setSwirldState(getSwirldState()); + + return newState; } + return this; } /** @@ -113,7 +140,7 @@ public boolean childHasExpectedType(final int index, final long childClassId) { */ @Override public int getMinimumSupportedVersion() { - return ClassVersion.ADD_MIN_GEN; + return ClassVersion.ADD_DUAL_STATE; } /** @@ -152,42 +179,6 @@ public void setPlatformState(final PlatformState platformState) { setChild(ChildIndices.PLATFORM_STATE, platformState); } - /** - * Get the dualState. - * - * @return the dualState - */ - private DualStateImpl getDualState() { - return getChild(ChildIndices.DUAL_STATE); - } - - /** - * Get current dualState object which can be read/written by the platform - * - * @return current dualState object which can be read/written by the platform - */ - public PlatformDualState getPlatformDualState() { - return getDualState(); - } - - /** - * Get current dualState object which can be read/written by the application - * - * @return current dualState object which can be read/written by the application - */ - public SwirldDualState getSwirldDualState() { - return getDualState(); - } - - /** - * Set the dual state. - * - * @param dualState the dual state - */ - public void setDualState(final DualStateImpl dualState) { - setChild(ChildIndices.DUAL_STATE, dualState); - } - /** * {@inheritDoc} */ @@ -201,7 +192,7 @@ public long getClassId() { */ @Override public int getVersion() { - return ClassVersion.ADD_DUAL_STATE; + return ClassVersion.REMOVE_DUAL_STATE; } /** @@ -245,8 +236,7 @@ public boolean equals(final Object other) { } final State state = (State) other; return Objects.equals(getPlatformState(), state.getPlatformState()) - && Objects.equals(getSwirldState(), state.getSwirldState()) - && Objects.equals(getPlatformDualState(), state.getPlatformDualState()); + && Objects.equals(getSwirldState(), state.getSwirldState()); } /** @@ -254,7 +244,7 @@ public boolean equals(final Object other) { */ @Override public int hashCode() { - return Objects.hash(getPlatformState(), getSwirldState(), getPlatformDualState()); + return Objects.hash(getPlatformState(), getSwirldState()); } /** @@ -263,27 +253,26 @@ public int hashCode() { * @param hashDepth the depth of the tree to visit and print */ public String getInfoString(final int hashDepth) { - final PlatformData data = getPlatformState().getPlatformData(); - final Hash epochHash = data.getNextEpochHash(); - final Hash hashEventsCons = data.getHashEventsCons(); - final List minGenInfo = data.getMinGenInfo(); - final ConsensusSnapshot snapshot = data.getSnapshot(); + final PlatformState platformState = getPlatformState(); + final Hash epochHash = platformState.getNextEpochHash(); + final Hash hashEventsCons = platformState.getRunningEventHash(); + final List minGenInfo = platformState.getMinGenInfo(); + final ConsensusSnapshot snapshot = platformState.getSnapshot(); final StringBuilder sb = new StringBuilder(); new TextTable() .setBordersEnabled(false) - .addRow("Round:", data.getRound()) - .addRow("Timestamp:", data.getConsensusTimestamp()) + .addRow("Round:", platformState.getRound()) + .addRow("Timestamp:", platformState.getConsensusTimestamp()) .addRow("Next consensus number:", snapshot == null ? "null" : snapshot.nextConsensusNumber()) .addRow("Running event hash:", hashEventsCons) .addRow("Running event mnemonic:", hashEventsCons == null ? "null" : hashEventsCons.toMnemonic()) - .addRow("Rounds non-ancient:", data.getRoundsNonAncient()) - .addRow("Creation version:", data.getCreationSoftwareVersion()) + .addRow("Rounds non-ancient:", platformState.getRoundsNonAncient()) + .addRow("Creation version:", platformState.getCreationSoftwareVersion()) .addRow("Epoch mnemonic:", epochHash == null ? "null" : epochHash.toMnemonic()) .addRow("Epoch hash:", epochHash) .addRow("Min gen hash code:", minGenInfo == null ? "null" : minGenInfo.hashCode()) - .addRow("Events hash code:", Arrays.hashCode(data.getEvents())) .addRow("Root hash:", getHash()) .render(sb); @@ -300,7 +289,6 @@ public String toString() { return new ToStringBuilder(this) .append("platformState", getPlatformState()) .append("swirldState", getSwirldState()) - .append("dualState", getPlatformDualState()) .toString(); } } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/SwirldStateManager.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/SwirldStateManager.java index c061903902ae..6f8260f40440 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/SwirldStateManager.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/SwirldStateManager.java @@ -32,7 +32,6 @@ import com.swirlds.platform.state.signed.SignedState; import com.swirlds.platform.system.Round; import com.swirlds.platform.system.SoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.address.AddressBook; import com.swirlds.platform.system.status.StatusActionSubmitter; @@ -174,7 +173,7 @@ public void prehandleSystemTransactions(final EventImpl event) { /** * Handles the events in a consensus round. Implementations are responsible for invoking - * {@link SwirldState#handleConsensusRound(Round, SwirldDualState)}. + * {@link SwirldState#handleConsensusRound(Round, PlatformState)}. * * @param round the round to handle */ @@ -183,7 +182,7 @@ public void handleConsensusRound(final ConsensusRound round) { uptimeTracker.handleRound( round, - state.getPlatformDualState().getMutableUptimeData(), + state.getPlatformState().getUptimeData(), state.getPlatformState().getAddressBook()); transactionHandler.handleRound(round, state); consensusSystemTransactionManager.handleRound(state, round); @@ -207,7 +206,9 @@ public State getConsensusState() { */ public void savedStateInFreezePeriod() { // set current DualState's lastFrozenTime to be current freezeTime - stateRef.get().getPlatformDualState().setLastFrozenTimeToBeCurrentFreezeTime(); + stateRef.get() + .getPlatformState() + .setLastFrozenTime(stateRef.get().getPlatformState().getFreezeTime()); } /** @@ -272,7 +273,7 @@ private void setLatestImmutableState(final State immutableState) { private void updateEpoch() { final PlatformState platformState = stateRef.get().getPlatformState(); if (platformState != null) { - platformState.getPlatformData().updateEpochHash(); + platformState.updateEpochHash(); } } @@ -281,7 +282,9 @@ private void updateEpoch() { */ @Override public boolean isInFreezePeriod(final Instant timestamp) { - return SwirldStateManagerUtils.isInFreezePeriod(timestamp, getConsensusState()); + final PlatformState platformState = getConsensusState().getPlatformState(); + return SwirldStateManagerUtils.isInFreezePeriod( + timestamp, platformState.getFreezeTime(), platformState.getLastFrozenTime()); } /** diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/SwirldStateManagerUtils.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/SwirldStateManagerUtils.java index fa863d6ec807..bc81b91db14f 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/SwirldStateManagerUtils.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/SwirldStateManagerUtils.java @@ -21,6 +21,7 @@ import com.swirlds.platform.metrics.SwirldStateMetrics; import com.swirlds.platform.system.SoftwareVersion; import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; import java.time.Instant; import java.util.Objects; @@ -51,7 +52,7 @@ public static State fastCopy( // Create a fast copy final State copy = state.copy(); - state.getPlatformState().getPlatformData().setCreationSoftwareVersion(softwareVersion); + state.getPlatformState().setCreationSoftwareVersion(softwareVersion); // Increment the reference count because this reference becomes the new value copy.reserve(); @@ -64,14 +65,27 @@ public static State fastCopy( } /** - * Determines if a {@code timestamp} is in a freeze period according to the provided state. + * Determines if a {@code timestamp} is in a freeze period according to the provided timestamps. * - * @param timestamp the timestamp to check - * @param consensusState the state that contains the freeze periods + * @param consensusTime the consensus time to check + * @param freezeTime the freeze time + * @param lastFrozenTime the last frozen time * @return true is the {@code timestamp} is in a freeze period */ - public static boolean isInFreezePeriod(final Instant timestamp, final State consensusState) { - final PlatformDualState dualState = consensusState.getPlatformDualState(); - return dualState != null && dualState.isInFreezePeriod(timestamp); + public static boolean isInFreezePeriod( + @NonNull final Instant consensusTime, + @Nullable final Instant freezeTime, + @Nullable final Instant lastFrozenTime) { + + // if freezeTime is not set, or consensusTime is before freezeTime, we are not in a freeze period + // if lastFrozenTime is equal to or after freezeTime, which means the nodes have been frozen once at/after the + // freezeTime, we are not in a freeze period + if (freezeTime == null || consensusTime.isBefore(freezeTime)) { + return false; + } + // Now we should check whether the nodes have been frozen at the freezeTime. + // when consensusTime is equal to or after freezeTime, + // and lastFrozenTime is before freezeTime, we are in a freeze period. + return lastFrozenTime == null || lastFrozenTime.isBefore(freezeTime); } } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/TransactionHandler.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/TransactionHandler.java index b914d2c6a1ca..6ea1cfd3e6e7 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/TransactionHandler.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/TransactionHandler.java @@ -81,7 +81,7 @@ public void handleRound(final ConsensusRound round, final State state) { final Instant timeOfHandle = Instant.now(); final long startTime = System.nanoTime(); - state.getSwirldState().handleConsensusRound(round, state.getSwirldDualState()); + state.getSwirldState().handleConsensusRound(round, state.getPlatformState()); final double secondsElapsed = (System.nanoTime() - startTime) * NANOSECONDS_TO_SECONDS; diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SavedStateMetadata.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SavedStateMetadata.java index 1583eab61b6a..3d443cabb126 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SavedStateMetadata.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SavedStateMetadata.java @@ -39,7 +39,6 @@ import com.swirlds.common.crypto.Hash; import com.swirlds.common.formatting.TextTable; import com.swirlds.common.platform.NodeId; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.PlatformState; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; @@ -175,23 +174,22 @@ public static SavedStateMetadata create( Objects.requireNonNull(now, "now must not be null"); final PlatformState platformState = signedState.getState().getPlatformState(); - final PlatformData platformData = platformState.getPlatformData(); final List signingNodes = signedState.getSigSet().getSigningNodes(); Collections.sort(signingNodes); - final Hash epochHash = platformData.getEpochHash(); + final Hash epochHash = platformState.getEpochHash(); return new SavedStateMetadata( signedState.getRound(), signedState.getState().getHash(), signedState.getState().getHash().toMnemonic(), - platformData.getSnapshot().nextConsensusNumber(), + platformState.getSnapshot().nextConsensusNumber(), signedState.getConsensusTimestamp(), - platformData.getHashEventsCons(), - platformData.getHashEventsCons().toMnemonic(), - platformData.getMinimumGenerationNonAncient(), - convertToString(platformData.getCreationSoftwareVersion()), + platformState.getRunningEventHash(), + platformState.getRunningEventHash().toMnemonic(), + platformState.getMinimumGenerationNonAncient(), + convertToString(platformState.getCreationSoftwareVersion()), now, selfId, signingNodes, diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedState.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedState.java index 8504299d71c8..978b2a5f2b83 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedState.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedState.java @@ -35,7 +35,6 @@ import com.swirlds.common.utility.RuntimeObjectRecord; import com.swirlds.common.utility.RuntimeObjectRegistry; import com.swirlds.common.utility.Threshold; -import com.swirlds.platform.internal.EventImpl; import com.swirlds.platform.state.MinGenInfo; import com.swirlds.platform.state.State; import com.swirlds.platform.state.signed.SignedStateHistory.SignedStateAction; @@ -216,7 +215,7 @@ public synchronized void setGarbageCollector( */ @Override public long getRound() { - return state.getPlatformState().getPlatformData().getRound(); + return state.getPlatformState().getRound(); } /** @@ -225,7 +224,7 @@ public long getRound() { * @return true if this is the genesis state */ public boolean isGenesisState() { - return state.getPlatformState().getPlatformData().getRound() == GENESIS_ROUND; + return state.getPlatformState().getRound() == GENESIS_ROUND; } /** @@ -438,7 +437,7 @@ public String toString() { * @return the consensus timestamp for this signed state. */ public @NonNull Instant getConsensusTimestamp() { - return state.getPlatformState().getPlatformData().getConsensusTimestamp(); + return state.getPlatformState().getConsensusTimestamp(); } /** @@ -457,22 +456,13 @@ public String toString() { return state.getSwirldState(); } - /** - * Get events in the platformState. - * - * @return events in the platformState - */ - public @Nullable EventImpl[] getEvents() { - return state.getPlatformState().getPlatformData().getEvents(); - } - /** * Get the hash of the consensus events in this state. * * @return the hash of the consensus events in this state */ public @NonNull Hash getHashEventsCons() { - return state.getPlatformState().getPlatformData().getHashEventsCons(); + return state.getPlatformState().getRunningEventHash(); } /** @@ -481,7 +471,7 @@ public String toString() { * @return the minimum generation of famous witnesses per round */ public @NonNull List getMinGenInfo() { - return state.getPlatformState().getPlatformData().getMinGenInfo(); + return state.getPlatformState().getMinGenInfo(); } /** @@ -493,7 +483,7 @@ public String toString() { * @throws NoSuchElementException if the generation information for this round is not contained withing this state */ public long getMinGen(final long round) { - return getState().getPlatformState().getPlatformData().getMinGen(round); + return getState().getPlatformState().getMinGen(round); } /** @@ -502,7 +492,7 @@ public long getMinGen(final long round) { * @return the generation of the oldest round */ public long getMinRoundGeneration() { - return getState().getPlatformState().getPlatformData().getMinRoundGeneration(); + return getState().getPlatformState().getMinRoundGeneration(); } /** diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateFileWriter.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateFileWriter.java index 001ebefb06f0..88f8c845e149 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateFileWriter.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateFileWriter.java @@ -163,7 +163,7 @@ public static void writeSignedStateFilesToDirectory( platformContext, selfId, directory, - signedState.getState().getPlatformState().getPlatformData().getMinimumGenerationNonAncient(), + signedState.getState().getPlatformState().getMinimumGenerationNonAncient(), signedState.getRound()); } } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateManager.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateManager.java index cbb87e51c9c6..7894bf817622 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateManager.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateManager.java @@ -204,10 +204,8 @@ public synchronized void addState(@NonNull final SignedState signedState) { } if (firstStateTimestamp.get() == null) { - firstStateTimestamp.set( - signedState.getState().getPlatformState().getPlatformData().getConsensusTimestamp()); - firstStateRound.set( - signedState.getState().getPlatformState().getPlatformData().getRound()); + firstStateTimestamp.set(signedState.getState().getPlatformState().getConsensusTimestamp()); + firstStateRound.set(signedState.getState().getPlatformState().getRound()); } // Double check that the signatures on this state are valid. diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateValidationData.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateValidationData.java index 08e668b3045f..6fa44b5fd7b9 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateValidationData.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/SignedStateValidationData.java @@ -17,7 +17,7 @@ package com.swirlds.platform.state.signed; import com.swirlds.common.crypto.Hash; -import com.swirlds.platform.state.PlatformData; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.address.AddressBook; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; @@ -44,12 +44,12 @@ public record SignedStateValidationData( @NonNull Hash consensusEventsRunningHash, @Nullable Hash epochHash) { - public SignedStateValidationData(@NonNull final PlatformData that, @Nullable final AddressBook addressBook) { + public SignedStateValidationData(@NonNull final PlatformState that, @Nullable final AddressBook addressBook) { this( that.getRound(), that.getConsensusTimestamp(), addressBook == null ? null : addressBook.getHash(), - that.getHashEventsCons(), + that.getRunningEventHash(), that.getEpochHash()); } diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/StartupStateUtils.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/StartupStateUtils.java index f9bd7fd6020c..cd50c552ef15 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/StartupStateUtils.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/state/signed/StartupStateUtils.java @@ -409,9 +409,8 @@ private static ReservedSignedState processRecoveryState( final Hash targetEpoch = emergencyRecoveryManager.getEmergencyRecoveryFile().hash(); final Hash stateHash = state == null ? null : state.get().getState().getHash(); - final Hash stateEpoch = state == null - ? null - : state.get().getState().getPlatformState().getPlatformData().getEpochHash(); + final Hash stateEpoch = + state == null ? null : state.get().getState().getPlatformState().getEpochHash(); final boolean inEpoch = isInEpoch(targetEpoch, stateHash, stateEpoch); @@ -433,7 +432,6 @@ private static ReservedSignedState processRecoveryState( state.get() .getState() .getPlatformState() - .getPlatformData() .setNextEpochHash( emergencyRecoveryManager.getEmergencyRecoveryFile().hash()); @@ -520,8 +518,7 @@ private static ReservedSignedState loadStateFile( final Hash oldHash = deserializedSignedState.originalHash(); final Hash newHash = rehashTree(state); - final SoftwareVersion loadedVersion = - state.getPlatformState().getPlatformData().getCreationSoftwareVersion(); + final SoftwareVersion loadedVersion = state.getPlatformState().getCreationSoftwareVersion(); if (oldHash.equals(newHash)) { logger.info(STARTUP.getMarker(), "Loaded state's hash is the same as when it was saved."); diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/DualState.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/DualState.java deleted file mode 100644 index b6153b4a2a5f..000000000000 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/DualState.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2016-2023 Hedera Hashgraph, LLC - * - * 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. - */ - -package com.swirlds.platform.system; - -import java.time.Instant; - -/** - * Contains any data that is either read or written by the platform and the application, - * and contains methods for reading or writing those data. - * The methods are available to both the platform and the application. - */ -public interface DualState { - /** - * Sets the instant after which the platform will enter FREEZING status. - * When consensus timestamp of a signed state is after this instant, - * the platform will stop creating events and accepting transactions. - * This is used to safely shut down the platform for maintenance. - * - * @param freezeTime - * an Instant in UTC - */ - void setFreezeTime(Instant freezeTime); - - /** - * Gets the time when the freeze starts - * - * @return the time when the freeze starts - */ - Instant getFreezeTime(); - - /** - * Gets the last freezeTime based on which the nodes were frozen - * - * @return the last freezeTime based on which the nodes were frozen - */ - Instant getLastFrozenTime(); -} diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/SwirldDualState.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/SwirldDualState.java deleted file mode 100644 index 6ae5afe0799b..000000000000 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/SwirldDualState.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2016-2023 Hedera Hashgraph, LLC - * - * 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. - */ - -package com.swirlds.platform.system; - -import edu.umd.cs.findbugs.annotations.NonNull; - -/** - * Contains any data that is either read or written by the platform and the application, - * and contains methods available to the application - */ -public interface SwirldDualState extends DualState { - - /** - * Get the node uptime data. - */ - @NonNull - UptimeData getUptimeData(); -} diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/SwirldState.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/SwirldState.java index bf4c6e4dc7a9..290c9e83f288 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/SwirldState.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/SwirldState.java @@ -17,13 +17,12 @@ package com.swirlds.platform.system; import com.swirlds.common.context.PlatformContext; -import com.swirlds.common.crypto.TransactionSignature; import com.swirlds.common.merkle.MerkleNode; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.address.AddressBook; import com.swirlds.platform.system.events.Event; import com.swirlds.platform.system.transaction.Transaction; import edu.umd.cs.findbugs.annotations.NonNull; -import java.util.List; import java.util.Objects; /** @@ -45,7 +44,7 @@ public interface SwirldState extends MerkleNode { *

* * @param platform the Platform that instantiated this state - * @param swirldDualState the dual state instance used by the initialization function + * @param platformState the platform state * @param trigger describes the reason why the state was created/recreated * @param previousSoftwareVersion the previous version of the software, {@link SoftwareVersion#NO_VERSION} if this * is genesis or if migrating from code from before the concept of an application @@ -53,7 +52,7 @@ public interface SwirldState extends MerkleNode { */ default void init( final Platform platform, - final SwirldDualState swirldDualState, + final PlatformState platformState, final InitTrigger trigger, final SoftwareVersion previousSoftwareVersion) { // Override if needed @@ -67,47 +66,23 @@ default void init( * actual public key, or attaching metadata. Additional signatures extracted from the transaction payload can also * be added to the list of signatures to be verified. *

- * If signature verification is desired, it is recommended that process be started in this method on a background - * thread using one of the methods below to give it time to complete before the transaction is handled - * post-consensus. - *

- *

* This method is always invoked on an immutable state. * * @param event the event to perform pre-handling on - * @see #handleConsensusRound(Round, SwirldDualState) */ default void preHandle(final Event event) {} /** - * {@inheritDoc} - *

- * The state of this object must NEVER change except inside the methods below. - * - *

- *

- * If signature verification was started on a background thread in {@link #preHandle(Event)}, the process - * should be checked for completion. Accessing {@link TransactionSignature#getSignatureStatus()} before this - * process is complete will cause it to return {@code null}: + * This method should apply the transactions in the provided round to the state. Only called on mutable states. * - *

-     *     for (TransactionSignature sig : transaction.getSignatures()) {
-     *         Future<Void> future = sig.waitForFuture().get();
-     *     }
-     * 
+ * @param round the round to apply + * @param platformState the platform state */ - void handleConsensusRound(final Round round, final SwirldDualState swirldDualState); + void handleConsensusRound(final Round round, final PlatformState platformState); /** * Implementations of the SwirldState should always override this method in production. The AddressBook returned - * should have the same Adddress entries as the configuration AddressBook, but with the weight values updated. + * should have the same Address entries as the configuration AddressBook, but with the weight values updated. *

* The default implementation of this method is provided for use in testing and to prevent compilation failure of * implementing classes that have not yet implemented this method. diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/state/notifications/NewSignedStateNotification.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/state/notifications/NewSignedStateNotification.java index a36ac0c1c27c..3a4584746de5 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/state/notifications/NewSignedStateNotification.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/system/state/notifications/NewSignedStateNotification.java @@ -17,7 +17,7 @@ package com.swirlds.platform.system.state.notifications; import com.swirlds.common.notification.AbstractNotification; -import com.swirlds.platform.system.DualState; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.SwirldState; import java.time.Instant; @@ -29,7 +29,7 @@ public class NewSignedStateNotification extends AbstractNotification { private final SwirldState swirldState; - private final DualState dualState; + private final PlatformState platformState; private final long round; private final Instant consensusTimestamp; @@ -37,18 +37,18 @@ public class NewSignedStateNotification extends AbstractNotification { * Create a notification for a newly signed state. * * @param swirldState the swirld state from the round that is now fully signed - * @param dualState the dual state from the round that is now fully signed + * @param platformState the platform state from the round that is now fully signed * @param round the round that is now fully signed * @param consensusTimestamp the consensus timestamp of the round that is now fully signed */ public NewSignedStateNotification( final SwirldState swirldState, - final DualState dualState, + final PlatformState platformState, final long round, final Instant consensusTimestamp) { this.swirldState = swirldState; - this.dualState = dualState; + this.platformState = platformState; this.round = round; this.consensusTimestamp = consensusTimestamp; } @@ -63,10 +63,10 @@ public T getSwirldState() { } /** - * Get the dual state from the round that is now fully signed. + * Get the platform state from the round that is now fully signed. */ - public DualState getDualState() { - return dualState; + public PlatformState getPlatformState() { + return platformState; } /** diff --git a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/util/BootstrapUtils.java b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/util/BootstrapUtils.java index 610a7bc3944e..ebcab160b676 100644 --- a/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/util/BootstrapUtils.java +++ b/platform-sdk/swirlds-platform-core/src/main/java/com/swirlds/platform/util/BootstrapUtils.java @@ -270,11 +270,7 @@ public static boolean detectSoftwareUpgrade( final SoftwareVersion loadedSoftwareVersion = loadedSignedState == null ? null - : loadedSignedState - .getState() - .getPlatformState() - .getPlatformData() - .getCreationSoftwareVersion(); + : loadedSignedState.getState().getPlatformState().getCreationSoftwareVersion(); final int versionComparison = loadedSoftwareVersion == null ? 1 : appVersion.compareTo(loadedSoftwareVersion); final boolean softwareUpgrade; if (versionComparison < 0) { diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/AddressBookInitializerTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/AddressBookInitializerTest.java index 988b31c82424..4302fe677acc 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/AddressBookInitializerTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/AddressBookInitializerTest.java @@ -34,7 +34,6 @@ import com.swirlds.common.platform.NodeId; import com.swirlds.common.test.fixtures.RandomAddressBookGenerator; import com.swirlds.platform.config.AddressBookConfig_; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.State; import com.swirlds.platform.state.address.AddressBookInitializer; @@ -340,10 +339,8 @@ private SignedState getMockSignedState( final SwirldState swirldState = getMockSwirldStateSupplier(weightValue).get(); when(signedState.getAddressBook()).thenReturn(stateAddressBook); when(signedState.getSwirldState()).thenReturn(swirldState); - final PlatformData platformData = mock(PlatformData.class); - when(platformData.getCreationSoftwareVersion()).thenReturn(softwareVersion); final PlatformState platformState = mock(PlatformState.class); - when(platformState.getPlatformData()).thenReturn(platformData); + when(platformState.getCreationSoftwareVersion()).thenReturn(softwareVersion); final State state = mock(State.class); when(state.getPlatformState()).thenReturn(platformState); when(signedState.getState()).thenReturn(state); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/SavedStateMetadataTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/SavedStateMetadataTests.java index ded222e73f30..8f7654760e0f 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/SavedStateMetadataTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/SavedStateMetadataTests.java @@ -43,7 +43,6 @@ import com.swirlds.common.platform.NodeId; import com.swirlds.common.test.fixtures.RandomUtils; import com.swirlds.platform.consensus.ConsensusSnapshot; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.State; import com.swirlds.platform.state.signed.SavedStateMetadata; @@ -224,15 +223,13 @@ void signingNodesSortedTest() { final State state = mock(State.class); when(state.getHash()).thenReturn(randomHash(random)); final PlatformState platformState = mock(PlatformState.class); - final PlatformData platformData = mock(PlatformData.class); - when(platformData.getHashEventsCons()).thenReturn(randomHash(random)); - when(platformData.getSnapshot()).thenReturn(mock(ConsensusSnapshot.class)); + when(platformState.getRunningEventHash()).thenReturn(randomHash(random)); + when(platformState.getSnapshot()).thenReturn(mock(ConsensusSnapshot.class)); final AddressBook addressBook = mock(AddressBook.class); when(signedState.getState()).thenReturn(state); when(state.getPlatformState()).thenReturn(platformState); when(platformState.getAddressBook()).thenReturn(addressBook); - when(platformState.getPlatformData()).thenReturn(platformData); when(signedState.getSigSet()).thenReturn(sigSet); when(sigSet.getSigningNodes()) .thenReturn(new ArrayList<>(List.of(new NodeId(3L), new NodeId(1L), new NodeId(2L)))); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/SwirldStateManagerFreezePeriodCheckerTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/SwirldStateManagerFreezePeriodCheckerTest.java index acce93b7f1b0..03a5434be4e1 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/SwirldStateManagerFreezePeriodCheckerTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/SwirldStateManagerFreezePeriodCheckerTest.java @@ -16,45 +16,42 @@ package com.swirlds.platform; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertTrue; -import com.swirlds.platform.state.DualStateImpl; -import com.swirlds.platform.state.State; import com.swirlds.platform.state.SwirldStateManagerUtils; -import com.swirlds.platform.system.address.AddressBook; import java.time.Instant; -import java.util.Collections; -import java.util.List; import org.junit.jupiter.api.Test; class SwirldStateManagerFreezePeriodCheckerTest { @Test void isInFreezePeriodTest() { - final State mockState = mock(State.class); - - final DualStateImpl mockDualState = mock(DualStateImpl.class); - final Instant consensusTime = Instant.now(); - - final AddressBook addressBook = mock(AddressBook.class); - when(addressBook.iterator()).thenReturn(Collections.emptyIterator()); - - when(mockState.getPlatformDualState()).thenReturn(null); - assertFalse( - SwirldStateManagerUtils.isInFreezePeriod(Instant.now(), mockState), - "when DualState is null, any Instant should not be in freezePeriod"); - - when(mockState.getPlatformDualState()).thenReturn(mockDualState); - for (boolean isInFreezeTime : List.of(true, false)) { - when(mockDualState.isInFreezePeriod(consensusTime)).thenReturn(isInFreezeTime); - assertEquals( - isInFreezeTime, - SwirldStateManagerUtils.isInFreezePeriod(consensusTime, mockState), - "swirldStateManager#isInFreezePeriod() should return the same result " - + "as current consensus DualState#isInFreezePeriod"); - } + + final Instant t1 = Instant.now(); + final Instant t2 = t1.plusSeconds(1); + final Instant t3 = t2.plusSeconds(1); + final Instant t4 = t3.plusSeconds(1); + + // No freeze time set + assertFalse(SwirldStateManagerUtils.isInFreezePeriod(t1, null, null)); + + // No freeze time set, previous freeze time set + assertFalse(SwirldStateManagerUtils.isInFreezePeriod(t2, null, t1)); + + // Freeze time is in the future, never frozen before + assertFalse(SwirldStateManagerUtils.isInFreezePeriod(t2, t3, null)); + + // Freeze time is in the future, frozen before + assertFalse(SwirldStateManagerUtils.isInFreezePeriod(t2, t3, t1)); + + // Freeze time is in the past, never frozen before + assertTrue(SwirldStateManagerUtils.isInFreezePeriod(t2, t1, null)); + + // Freeze time is in the past, frozen before at an earlier time + assertTrue(SwirldStateManagerUtils.isInFreezePeriod(t3, t2, t1)); + + // Freeze time in the past, already froze at that exact time + assertFalse(SwirldStateManagerUtils.isInFreezePeriod(t3, t2, t2)); } } diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/consensus/RoundCalculationUtilsTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/consensus/RoundCalculationUtilsTest.java index a3ccd644f6a5..4b8ab3f9bb4a 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/consensus/RoundCalculationUtilsTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/consensus/RoundCalculationUtilsTest.java @@ -18,7 +18,6 @@ import static org.mockito.Mockito.when; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.State; import com.swirlds.platform.state.signed.SignedState; @@ -72,16 +71,14 @@ void getMinGenNonAncientFromSignedState() { final SignedState signedState = Mockito.mock(SignedState.class); final State state = Mockito.mock(State.class); final PlatformState platformState = Mockito.mock(PlatformState.class); - final PlatformData platformData = Mockito.mock(PlatformData.class); when(signedState.getState()).thenReturn(state); when(state.getPlatformState()).thenReturn(platformState); - when(platformState.getPlatformData()).thenReturn(platformData); final AtomicLong lastRoundDecided = new AtomicLong(); when(signedState.getRound()).thenAnswer(a -> lastRoundDecided.get()); when(signedState.getMinGen(Mockito.anyLong())).thenAnswer(a -> map.get(a.getArgument(0, Long.class))); - when(platformData.getRound()).thenAnswer(a -> lastRoundDecided.get()); - when(platformData.getMinGen(Mockito.anyLong())).thenAnswer(a -> map.get(a.getArgument(0, Long.class))); + when(platformState.getRound()).thenAnswer(a -> lastRoundDecided.get()); + when(platformState.getMinGen(Mockito.anyLong())).thenAnswer(a -> map.get(a.getArgument(0, Long.class))); lastRoundDecided.set(10); Assertions.assertEquals( diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/eventhandling/ConsensusRoundHandlerTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/eventhandling/ConsensusRoundHandlerTests.java index d98ebecc0fcc..aac4457aedc0 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/eventhandling/ConsensusRoundHandlerTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/eventhandling/ConsensusRoundHandlerTests.java @@ -36,8 +36,6 @@ import com.swirlds.platform.internal.ConsensusRound; import com.swirlds.platform.internal.EventImpl; import com.swirlds.platform.metrics.SwirldStateMetrics; -import com.swirlds.platform.state.DualStateImpl; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.State; import com.swirlds.platform.state.SwirldStateManager; @@ -194,15 +192,6 @@ private void initConsensusHandler(final SwirldState swirldState) { state.setPlatformState(platformState); - final DualStateImpl platformDualState = mock(DualStateImpl.class); - when(platformDualState.getClassId()).thenReturn(DualStateImpl.CLASS_ID); - when(platformDualState.copy()).thenReturn(platformDualState); - - state.setDualState(platformDualState); - - final PlatformData platformData = mock(PlatformData.class); - when(platformState.getPlatformData()).thenReturn(platformData); - final Configuration configuration = new TestConfigBuilder() .withValue(EventConfig_.MAX_EVENT_QUEUE_FOR_CONS, 500) .getOrCreateConfig(); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/DefaultSignedStateValidatorTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/DefaultSignedStateValidatorTests.java index 4c6d6110994a..6c57533222d4 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/DefaultSignedStateValidatorTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/DefaultSignedStateValidatorTests.java @@ -247,8 +247,8 @@ void testSignedStateValidationRandom(final String desc, final List nodes, validator = new DefaultSignedStateValidator(platformContext); final SignedState signedState = stateSignedByNodes(signingNodes); - final SignedStateValidationData originalData = new SignedStateValidationData( - signedState.getState().getPlatformState().getPlatformData(), addressBook); + final SignedStateValidationData originalData = + new SignedStateValidationData(signedState.getState().getPlatformState(), addressBook); final boolean shouldSucceed = stateHasEnoughWeight(nodes, signingNodes); if (shouldSucceed) { diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/ReconnectTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/ReconnectTest.java index 5af32105a982..0860bf63dd33 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/ReconnectTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/ReconnectTest.java @@ -126,7 +126,6 @@ private void executeReconnect(final ReconnectMetrics reconnectMetrics) throws In .build(); final MerkleCryptography cryptography = MerkleCryptoFactory.getInstance(); - cryptography.digestSync(signedState.getState().getPlatformState()); cryptography.digestSync(signedState.getState()); final ReconnectLearner receiver = buildReceiver( diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/emergency/EmergencySignedStateValidatorTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/emergency/EmergencySignedStateValidatorTests.java index 6ed39a784556..90e44f11950e 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/emergency/EmergencySignedStateValidatorTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/reconnect/emergency/EmergencySignedStateValidatorTests.java @@ -130,10 +130,7 @@ void stateMatchesRoundAndHash() { } private void assertNextEpochHashEquals(final Hash hash, final SignedState signedState, final String msg) { - assertEquals( - hash, - signedState.getState().getPlatformState().getPlatformData().getNextEpochHash(), - msg); + assertEquals(hash, signedState.getState().getPlatformState().getNextEpochHash(), msg); } /** @@ -154,7 +151,7 @@ void validLaterState() { .build(); final Hash emergencyHash = RandomUtils.randomHash(random); - laterState.getState().getPlatformState().getPlatformData().setEpochHash(emergencyHash); + laterState.getState().getPlatformState().setEpochHash(emergencyHash); validator = new EmergencySignedStateValidator( STATE_CONFIG, @@ -184,7 +181,7 @@ void invalidLaterStateWrongEpochHash() { final Hash emergencyHash = RandomUtils.randomHash(random); final Hash badEpochHash = RandomUtils.randomHash(random); - laterState.getState().getPlatformState().getPlatformData().setNextEpochHash(badEpochHash); + laterState.getState().getPlatformState().setNextEpochHash(badEpochHash); validator = new EmergencySignedStateValidator( STATE_CONFIG, @@ -215,7 +212,7 @@ void invalidLaterStateNotSignedByMajority() { .build(); final Hash emergencyHash = RandomUtils.randomHash(random); - laterState.getState().getPlatformState().getPlatformData().setEpochHash(emergencyHash); + laterState.getState().getPlatformState().setEpochHash(emergencyHash); validator = new EmergencySignedStateValidator( STATE_CONFIG, diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/recovery/EventRecoveryWorkflowTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/recovery/EventRecoveryWorkflowTests.java index dd2f80c3108b..6743cce45439 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/recovery/EventRecoveryWorkflowTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/recovery/EventRecoveryWorkflowTests.java @@ -38,8 +38,8 @@ import com.swirlds.common.test.fixtures.RandomUtils; import com.swirlds.platform.internal.EventImpl; import com.swirlds.platform.recovery.emergencyfile.EmergencyRecoveryFile; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.events.ConsensusEvent; import com.swirlds.test.framework.config.TestConfigBuilder; @@ -105,7 +105,7 @@ void isFreezeStateTest() { @Test @DisplayName("applyTransactions() Test") void applyTransactionsTest() { - final SwirldDualState dualState = mock(SwirldDualState.class); + final PlatformState platformState = mock(PlatformState.class); final List events = new ArrayList<>(); for (int i = 0; i < 100; i++) { @@ -143,14 +143,14 @@ void applyTransactionsTest() { doAnswer(invocation -> { assertFalse(roundHandled.get(), "round should only be handled once"); assertSame(round, invocation.getArgument(0), "unexpected round"); - assertSame(dualState, invocation.getArgument(1), "unexpected dual state"); + assertSame(platformState, invocation.getArgument(1), "unexpected dual state"); roundHandled.set(true); return null; }) .when(mutableState) .handleConsensusRound(any(), any()); - EventRecoveryWorkflow.applyTransactions(immutableState, mutableState, dualState, round); + EventRecoveryWorkflow.applyTransactions(immutableState, mutableState, platformState, round); assertEquals(events.size(), preHandleList.size(), "incorrect number of pre-handle calls"); for (int index = 0; index < events.size(); index++) { diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/DualStateImplTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/DualStateImplTest.java deleted file mode 100644 index 7bd83eadeb24..000000000000 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/DualStateImplTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2021-2023 Hedera Hashgraph, LLC - * - * 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. - */ - -package com.swirlds.platform.state; - -import static java.time.temporal.ChronoUnit.DAYS; -import static java.time.temporal.ChronoUnit.HOURS; -import static java.time.temporal.ChronoUnit.MICROS; -import static java.time.temporal.ChronoUnit.MILLIS; -import static java.time.temporal.ChronoUnit.MINUTES; -import static java.time.temporal.ChronoUnit.NANOS; -import static java.time.temporal.ChronoUnit.SECONDS; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.List; -import org.junit.jupiter.api.Test; - -class DualStateImplTest { - private static final int TIME_DIFF = 1; - - static final List timeUnits = List.of(NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS, DAYS); - - private final Instant freezeTime = Instant.now(); - - @Test - void isInFreezePeriodTest() { - final DualStateImpl dualState = new DualStateImpl(); - assertFalse( - dualState.isInFreezePeriod(Instant.now()), - "when freezeTime is null, any Instant should not be in freezePeriod"); - - dualState.setFreezeTime(freezeTime); - - // when lastFrozenTime is null - for (ChronoUnit unit : timeUnits) { - assertFalse( - dualState.isInFreezePeriod(freezeTime.minus(TIME_DIFF, unit)), - "Instant before freeze time should not be in freeze period"); - - assertTrue( - dualState.isInFreezePeriod(freezeTime), - "when lastFrozenTime is null, Instant the same as freeze time should be in freeze period"); - - assertTrue( - dualState.isInFreezePeriod(freezeTime.plus(TIME_DIFF, unit)), - "when lastFrozenTime is null, Instant after freeze time should be in freeze period"); - } - - // when lastFrozenTime is the same as freezeTime - dualState.setLastFrozenTime(freezeTime); - for (ChronoUnit unit : timeUnits) { - assertFalse( - dualState.isInFreezePeriod(freezeTime.minus(TIME_DIFF, unit)), - "Instant before freeze time should not be in freeze period"); - assertFalse( - dualState.isInFreezePeriod(this.freezeTime), - "when lastFrozenTime is the same as freezeTime, any Instant should be not in freeze period"); - assertFalse( - dualState.isInFreezePeriod(freezeTime.plus(TIME_DIFF, unit)), - "when lastFrozenTime is the same as freezeTime, any Instant should not be in freeze period"); - } - - // when lastFrozenTime is after freezeTime - for (ChronoUnit unit : timeUnits) { - dualState.setLastFrozenTime(freezeTime.plus(TIME_DIFF * 2, unit)); - assertFalse( - dualState.isInFreezePeriod(freezeTime.minus(TIME_DIFF, unit)), - "Instant before freeze time should not be in freeze period"); - assertFalse( - dualState.isInFreezePeriod(this.freezeTime), - "when lastFrozenTime is after freezeTime, any Instant should be not in freeze period"); - assertFalse( - dualState.isInFreezePeriod(freezeTime.plus(TIME_DIFF, unit)), - "when lastFrozenTime is after freezeTime, any Instant should not be in freeze period"); - } - } -} diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/RandomSignedStateGenerator.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/RandomSignedStateGenerator.java index 9897985b24ce..9689db4babdf 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/RandomSignedStateGenerator.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/RandomSignedStateGenerator.java @@ -113,9 +113,8 @@ public SignedState build() { final DummySwirldState swirldState = new DummySwirldState(addressBookInstance); stateInstance.setSwirldState(swirldState); PlatformState platformState = new PlatformState(); - final PlatformData platformData = new PlatformData(); - platformData.setEpochHash(epoch); - platformState.setPlatformData(platformData); + platformState.setAddressBook(addressBookInstance); + platformState.setEpochHash(epoch); stateInstance.setPlatformState(platformState); } else { stateInstance = state; @@ -163,23 +162,21 @@ public SignedState build() { softwareVersionInstance = softwareVersion; } - stateInstance.getPlatformState().setAddressBook(addressBookInstance); - stateInstance - .getPlatformState() - .getPlatformData() - .setRound(roundInstance) - .setHashEventsCons(hashEventsConsInstance) - .setConsensusTimestamp(consensusTimestampInstance) - .setCreationSoftwareVersion(softwareVersionInstance) - .setRoundsNonAncient(roundsNonAncientInstance) - .setSnapshot(new ConsensusSnapshot( - roundInstance, - Stream.generate(() -> randomHash(random)).limit(10).toList(), - IntStream.range(0, roundsNonAncientInstance) - .mapToObj(i -> new MinGenInfo(roundInstance - i, 0L)) - .toList(), - roundInstance, - consensusTimestampInstance)); + final PlatformState platformState = stateInstance.getPlatformState(); + + platformState.setRound(roundInstance); + platformState.setRunningEventHash(hashEventsConsInstance); + platformState.setConsensusTimestamp(consensusTimestampInstance); + platformState.setCreationSoftwareVersion(softwareVersionInstance); + platformState.setRoundsNonAncient(roundsNonAncientInstance); + platformState.setSnapshot(new ConsensusSnapshot( + roundInstance, + Stream.generate(() -> randomHash(random)).limit(10).toList(), + IntStream.range(0, roundsNonAncientInstance) + .mapToObj(i -> new MinGenInfo(roundInstance - i, 0L)) + .toList(), + roundInstance, + consensusTimestampInstance)); final SignedState signedState = new SignedState( new TestConfigBuilder() diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SignedStateTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SignedStateTests.java index 7a952b588fba..cd94bcd97beb 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SignedStateTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SignedStateTests.java @@ -69,9 +69,7 @@ private State buildMockState(final Runnable reserveCallback, final Runnable rele final State state = spy(new State()); final SwirldState swirldState = mock(SwirldState.class); - final PlatformData platformData = new PlatformData(); final PlatformState platformState = new PlatformState(); - platformState.setPlatformData(platformData); platformState.setAddressBook(mock(AddressBook.class)); when(state.getPlatformState()).thenReturn(platformState); @@ -279,9 +277,7 @@ void alternateConstructorReservationsTest() { final State state = spy(new State()); final PlatformState platformState = mock(PlatformState.class); when(state.getPlatformState()).thenReturn(platformState); - final PlatformData platformData = mock(PlatformData.class); - when(platformState.getPlatformData()).thenReturn(platformData); - when(platformData.getRound()).thenReturn(0L); + when(platformState.getRound()).thenReturn(0L); final SignedState signedState = new SignedState(TestPlatformContextBuilder.create().build(), state, "test", false); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SwirldStateManagerTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SwirldStateManagerTests.java index a799d4fa8789..a168b588cc60 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SwirldStateManagerTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SwirldStateManagerTests.java @@ -119,9 +119,6 @@ private static State newState() { when(platformState.getClassId()).thenReturn(PlatformState.CLASS_ID); when(platformState.copy()).thenReturn(platformState); - final PlatformData platformData = mock(PlatformData.class); - when(platformState.getPlatformData()).thenReturn(platformData); - state.setPlatformState(platformState); assertEquals(0, state.getReservationCount(), "A brand new state should have no references."); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SwirldStateManagerUtilsTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SwirldStateManagerUtilsTests.java index 6be8d4c17c53..4075158d2db3 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SwirldStateManagerUtilsTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/SwirldStateManagerUtilsTests.java @@ -43,15 +43,9 @@ void testFastCopyIsMutable() { when(platformState.copy()).thenReturn(platformState); state.setPlatformState(platformState); - final PlatformData platformData = mock(PlatformData.class); - when(platformState.getPlatformData()).thenReturn(platformData); - final SwirldState swirldState = new DummySwirldState(); state.setSwirldState(swirldState); - final DualStateImpl dualState = new DualStateImpl(); - state.setDualState(dualState); - state.reserve(); final SwirldStateMetrics stats = mock(SwirldStateMetrics.class); final State result = SwirldStateManagerUtils.fastCopy(state, stats, new BasicSoftwareVersion(1)); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/TransactionHandlerTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/TransactionHandlerTest.java index 3928cb3dbbd6..d4e44da4614f 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/TransactionHandlerTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/TransactionHandlerTest.java @@ -28,7 +28,6 @@ import com.swirlds.platform.internal.EventImpl; import com.swirlds.platform.metrics.SwirldStateMetrics; import com.swirlds.platform.system.BasicSoftwareVersion; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.events.BaseEventHashedData; import com.swirlds.platform.system.events.BaseEventUnhashedData; @@ -55,13 +54,13 @@ class TransactionHandlerTest { private final State state = mock(State.class); private final SwirldState swirldState = mock(SwirldState.class); - private final SwirldDualState dualState = mock(SwirldDualState.class); + private final PlatformState platformState = mock(PlatformState.class); private TransactionHandler handler; @BeforeEach void setup() { - when(state.getSwirldDualState()).thenReturn(dualState); + when(state.getPlatformState()).thenReturn(platformState); handler = new TransactionHandler(selfId, mock(SwirldStateMetrics.class)); } diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/AddIncompleteStateTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/AddIncompleteStateTest.java index 38d50f9b5596..64d6a2594443 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/AddIncompleteStateTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/AddIncompleteStateTest.java @@ -113,10 +113,8 @@ void addIncompleteStateTest() { manager.addState(stateFromDisk); assertEquals( - stateFromDisk.getState().getPlatformState().getPlatformData().getConsensusTimestamp(), - manager.getFirstStateTimestamp()); - assertEquals( - stateFromDisk.getState().getPlatformState().getPlatformData().getRound(), manager.getFirstStateRound()); + stateFromDisk.getState().getPlatformState().getConsensusTimestamp(), manager.getFirstStateTimestamp()); + assertEquals(stateFromDisk.getState().getPlatformState().getRound(), manager.getFirstStateRound()); assertNull(manager.getLatestSignedState("test")); assertEquals(-1, manager.getLastCompleteRound()); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/EarlySignaturesTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/EarlySignaturesTest.java index 3bbc054d05d3..3e58b542c991 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/EarlySignaturesTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/EarlySignaturesTest.java @@ -143,11 +143,7 @@ void earlySignaturesTest() throws InterruptedException { manager.addState(signedState); if (round == 0) { - firstTimestamp = signedState - .getState() - .getPlatformState() - .getPlatformData() - .getConsensusTimestamp(); + firstTimestamp = signedState.getState().getPlatformState().getConsensusTimestamp(); } assertEquals(firstTimestamp, manager.getFirstStateTimestamp()); assertEquals(firstRound, manager.getFirstStateRound()); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/RegisterStatesWithoutSignaturesTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/RegisterStatesWithoutSignaturesTest.java index aa01f2f82df9..e35546589209 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/RegisterStatesWithoutSignaturesTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/RegisterStatesWithoutSignaturesTest.java @@ -103,11 +103,7 @@ void registerStatesWithoutSignatures() throws InterruptedException { manager.addState(signedState); if (round == 0) { - firstTimestamp = signedState - .getState() - .getPlatformState() - .getPlatformData() - .getConsensusTimestamp(); + firstTimestamp = signedState.getState().getPlatformState().getConsensusTimestamp(); } assertEquals(firstTimestamp, manager.getFirstStateTimestamp()); assertEquals(firstRound, manager.getFirstStateRound()); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/SequentialSignaturesTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/SequentialSignaturesTest.java index d3c8b681982d..7911437ced59 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/SequentialSignaturesTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/manager/SequentialSignaturesTest.java @@ -104,11 +104,7 @@ void sequentialSignaturesTest() throws InterruptedException { manager.addState(signedState); if (round == 0) { - firstTimestamp = signedState - .getState() - .getPlatformState() - .getPlatformData() - .getConsensusTimestamp(); + firstTimestamp = signedState.getState().getPlatformState().getConsensusTimestamp(); } assertEquals(firstTimestamp, manager.getFirstStateTimestamp()); assertEquals(firstRound, manager.getFirstStateRound()); diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/signed/StartupStateUtilsTests.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/signed/StartupStateUtilsTests.java index 06e174a6a36c..9844f2891327 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/signed/StartupStateUtilsTests.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/state/signed/StartupStateUtilsTests.java @@ -458,13 +458,12 @@ void noStateHasEpochHashPreviousRoundExistsTest(final int startingStateIndex) assertEquals(targetState.getRound(), loadedState.getRound()); assertEquals(targetState.getState().getHash(), loadedState.getState().getHash()); - assertNull(loadedState.getState().getPlatformState().getPlatformData().getEvents()); // As a sanity check, make sure the consensus timestamp is the same. This is generated randomly, so if this // matches then it's a good signal that the correct state was loaded. assertEquals( - targetState.getState().getPlatformState().getPlatformData().getConsensusTimestamp(), - loadedState.getState().getPlatformState().getPlatformData().getConsensusTimestamp()); + targetState.getState().getPlatformState().getConsensusTimestamp(), + loadedState.getState().getPlatformState().getConsensusTimestamp()); assertFalse(emergencyStateLoaded.get()); } @@ -701,12 +700,8 @@ void recoveryCorruptedStateRecyclingPermittedTest(final int invalidStateCount) // As a sanity check, make sure the consensus timestamp is the same. This is generated randomly, so if this // matches then it's a good signal that the correct state was loaded. assertEquals( - latestUncorruptedState - .getState() - .getPlatformState() - .getPlatformData() - .getConsensusTimestamp(), - loadedState.getState().getPlatformState().getPlatformData().getConsensusTimestamp()); + latestUncorruptedState.getState().getPlatformState().getConsensusTimestamp(), + loadedState.getState().getPlatformState().getConsensusTimestamp()); } else { assertNull(loadedState); } diff --git a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/util/HashLoggerTest.java b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/util/HashLoggerTest.java index 6a7e6b39385c..11a7740fc62d 100644 --- a/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/util/HashLoggerTest.java +++ b/platform-sdk/swirlds-platform-core/src/test/java/com/swirlds/platform/util/HashLoggerTest.java @@ -30,7 +30,6 @@ import com.swirlds.common.merkle.MerkleNode; import com.swirlds.common.merkle.crypto.MerkleCryptoFactory; import com.swirlds.common.test.merkle.util.MerkleTestUtils; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.State; import com.swirlds.platform.state.signed.SignedState; @@ -155,13 +154,11 @@ private SignedState createSignedState(final long round) { final AddressBook addressBook = new AddressBook(); addressBook.setHash(merkleNode.getHash()); - final PlatformData platformData = new PlatformData(); - platformData.setRound(round); - platformData.setHash(merkleNode.getHash()); - final PlatformState platformState = new PlatformState(); - platformState.setChild(0, platformData); - platformState.setChild(1, addressBook); + + platformState.setRound(round); + platformState.setHash(merkleNode.getHash()); + platformState.setAddressBook(addressBook); when(state.getPlatformState()).thenReturn(platformState); when(state.getRoute()).thenReturn(merkleNode.getRoute()); diff --git a/platform-sdk/swirlds-platform-core/src/testFixtures/java/com/swirlds/platform/test/fixtures/event/EventUtils.java b/platform-sdk/swirlds-platform-core/src/testFixtures/java/com/swirlds/platform/test/fixtures/event/EventUtils.java index 4ab1743a712f..78daf428d029 100644 --- a/platform-sdk/swirlds-platform-core/src/testFixtures/java/com/swirlds/platform/test/fixtures/event/EventUtils.java +++ b/platform-sdk/swirlds-platform-core/src/testFixtures/java/com/swirlds/platform/test/fixtures/event/EventUtils.java @@ -18,18 +18,8 @@ import static java.lang.Integer.max; -import com.swirlds.common.constructable.ConstructableRegistry; -import com.swirlds.common.constructable.ConstructableRegistryException; -import com.swirlds.common.crypto.Hash; import com.swirlds.common.platform.NodeId; -import com.swirlds.common.test.fixtures.merkle.util.MerkleSerializeUtils; -import com.swirlds.platform.internal.EventImpl; -import com.swirlds.platform.state.State; -import com.swirlds.platform.state.signed.SignedState; -import com.swirlds.test.framework.context.TestPlatformContextBuilder; import edu.umd.cs.findbugs.annotations.NonNull; -import java.io.IOException; -import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -41,74 +31,6 @@ public abstract class EventUtils { - /** - * Creates a copy of the supplies SignedState to simulate a restart or reconnect - * - * @param signedState the state to copy - * @return a copy of the state - */ - public static SignedState serializeDeserialize(final Path dir, final SignedState signedState) - throws ConstructableRegistryException, IOException { - final ConstructableRegistry registry = ConstructableRegistry.getInstance(); - registry.registerConstructables("com.swirlds.platform.state"); - registry.registerConstructables("com.swirlds.common.*"); - final State stateCopy = MerkleSerializeUtils.serializeDeserialize(dir, signedState.getState()); - final SignedState signedStateCopy = - new SignedState(TestPlatformContextBuilder.create().build(), stateCopy, "test", false); - signedStateCopy.setSigSet(signedState.getSigSet()); - return signedStateCopy; - } - - /** - * Converts events in the SignedState to IndexedEvent - * - * @param signedState the state where events are stored - */ - public static void convertEvents(final SignedState signedState) { - final EventImpl[] events = - signedState.getState().getPlatformState().getPlatformData().getEvents(); - for (int i = 0; i < events.length; i++) { - final IndexedEvent ie = new IndexedEvent(events[i]); - events[i] = ie; - } - State.linkParents(events); - } - - /** - * Get a map from creator sequence pairs to the corresponding event. - * - * @param events - * an array of events - */ - public static Map getEventMap(final EventImpl[] events) { - final Map map = new HashMap<>(); - for (final EventImpl event : events) { - map.put(event.getBaseHash(), event); - } - return map; - } - - /** - * Find the max generation number for each node in a sequence of events. Assumes events are sorted and that there - * are no forks. - * - * @param events - * a list of events - * @param numberOfNodes - * the total number of nodes - * @return a map containing the max generation number for each node - */ - @NonNull - public static Map getLastGenerationInState( - @NonNull final EventImpl[] events, final int numberOfNodes) { - Objects.requireNonNull(events, "events must not be null"); - final Map last = new HashMap<>(numberOfNodes); - for (final EventImpl event : events) { - last.put(event.getCreatorId(), event.getGeneration()); - } - return last; - } - /** * Choose a random integer given a list of probabilistic weights. * diff --git a/platform-sdk/swirlds-platform-core/src/testFixtures/java/com/swirlds/platform/test/fixtures/state/DummySwirldState.java b/platform-sdk/swirlds-platform-core/src/testFixtures/java/com/swirlds/platform/test/fixtures/state/DummySwirldState.java index 407d26591e4e..a03083d47fd6 100644 --- a/platform-sdk/swirlds-platform-core/src/testFixtures/java/com/swirlds/platform/test/fixtures/state/DummySwirldState.java +++ b/platform-sdk/swirlds-platform-core/src/testFixtures/java/com/swirlds/platform/test/fixtures/state/DummySwirldState.java @@ -20,8 +20,8 @@ import com.swirlds.common.io.streams.SerializableDataInputStream; import com.swirlds.common.io.streams.SerializableDataOutputStream; +import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.Round; -import com.swirlds.platform.system.SwirldDualState; import com.swirlds.platform.system.SwirldState; import com.swirlds.platform.system.address.AddressBook; import java.io.IOException; @@ -85,7 +85,7 @@ public AddressBook getAddressBookCopy() { } @Override - public void handleConsensusRound(final Round round, final SwirldDualState swirldDualState) { + public void handleConsensusRound(final Round round, final PlatformState platformState) { // intentionally does nothing } diff --git a/platform-sdk/swirlds-platform-core/src/testFixtures/java/module-info.java b/platform-sdk/swirlds-platform-core/src/testFixtures/java/module-info.java index 56de115a7b9c..bcb4ba89fd29 100644 --- a/platform-sdk/swirlds-platform-core/src/testFixtures/java/module-info.java +++ b/platform-sdk/swirlds-platform-core/src/testFixtures/java/module-info.java @@ -3,7 +3,6 @@ requires transitive com.swirlds.common; requires transitive com.swirlds.platform.core; requires com.swirlds.logging; - requires com.swirlds.test.framework; requires org.apache.logging.log4j; requires org.junit.jupiter.api; requires static com.github.spotbugs.annotations; diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/PlatformStateUtils.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/PlatformStateUtils.java index d742f98ed89a..9c2455cd0df5 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/PlatformStateUtils.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/PlatformStateUtils.java @@ -23,7 +23,6 @@ import com.swirlds.common.test.fixtures.RandomAddressBookGenerator.WeightDistributionStrategy; import com.swirlds.platform.consensus.ConsensusSnapshot; import com.swirlds.platform.state.MinGenInfo; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.system.address.AddressBook; import java.util.LinkedList; @@ -46,8 +45,6 @@ public static PlatformState randomPlatformState() { */ public static PlatformState randomPlatformState(final Random random) { final PlatformState platformState = new PlatformState(); - final PlatformData platformData = new PlatformData(); - platformState.setPlatformData(platformData); final AddressBook addressBook = new RandomAddressBookGenerator() .setSize(4) @@ -55,22 +52,20 @@ public static PlatformState randomPlatformState(final Random random) { .build(); platformState.setAddressBook(addressBook); - platformData.setHashEventsCons(randomHash(random)); - platformData.setRound(random.nextLong()); - platformData.setConsensusTimestamp(randomInstant(random)); + platformState.setRunningEventHash(randomHash(random)); + platformState.setRound(random.nextLong()); + platformState.setConsensusTimestamp(randomInstant(random)); final List minGenInfo = new LinkedList<>(); for (int index = 0; index < 10; index++) { minGenInfo.add(new MinGenInfo(random.nextLong(), random.nextLong())); } - platformState - .getPlatformData() - .setSnapshot(new ConsensusSnapshot( - random.nextLong(), - List.of(randomHash(random), randomHash(random), randomHash(random)), - minGenInfo, - random.nextLong(), - randomInstant(random))); + platformState.setSnapshot(new ConsensusSnapshot( + random.nextLong(), + List.of(randomHash(random), randomHash(random), randomHash(random)), + minGenInfo, + random.nextLong(), + randomInstant(random))); return platformState; } diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/ConsensusUtils.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/ConsensusUtils.java index 1f71ddae2ccd..9594c0c6175f 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/ConsensusUtils.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/ConsensusUtils.java @@ -23,7 +23,6 @@ import com.swirlds.platform.internal.ConsensusRound; import com.swirlds.platform.internal.EventImpl; import com.swirlds.platform.metrics.ConsensusMetrics; -import com.swirlds.platform.state.signed.SignedState; import com.swirlds.platform.system.address.Address; import com.swirlds.platform.system.address.AddressBook; import com.swirlds.platform.test.NoOpConsensusMetrics; @@ -65,18 +64,6 @@ public static ConsensusImpl buildSimpleConsensus(final AddressBook addressBook) ConfigurationHolder.getConfigData(ConsensusConfig.class), NOOP_CONSENSUS_METRICS, addressBook); } - /** - * Load events from a signed state into a generator, so that they can be used as other parents - * - * @param signedState the source of events - * @param generator the generator to load into to - * @param random a source of randomness - */ - public static void loadEventsIntoGenerator( - final SignedState signedState, final GraphGenerator generator, final Random random) { - loadEventsIntoGenerator(signedState.getEvents(), generator, random); - } - public static void loadEventsIntoGenerator( final EventImpl[] events, final GraphGenerator generator, final Random random) { Instant lastTimestamp = Instant.MIN; diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/TestIntake.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/TestIntake.java index 7c004513a30f..8e32b895b4fe 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/TestIntake.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/TestIntake.java @@ -49,7 +49,6 @@ import com.swirlds.test.framework.context.TestPlatformContextBuilder; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; -import java.util.Arrays; import java.util.Deque; import java.util.List; @@ -184,7 +183,6 @@ public void addLinkedEvent(@NonNull final EventImpl event) { public void loadFromSignedState(@NonNull final SignedState signedState) { consensus.loadFromSignedState(signedState); shadowGraph.clear(); - shadowGraph.initFromEvents(Arrays.asList(signedState.getEvents()), consensus.getMinRoundGeneration()); } public void loadSnapshot(@NonNull final ConsensusSnapshot snapshot) { diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/framework/ConsensusTestNode.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/framework/ConsensusTestNode.java index 03a6ddf2a80d..cbfe6dd9261d 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/framework/ConsensusTestNode.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/framework/ConsensusTestNode.java @@ -20,8 +20,6 @@ import com.swirlds.platform.Consensus; import com.swirlds.platform.consensus.ConsensusSnapshot; -import com.swirlds.platform.state.signed.SignedState; -import com.swirlds.platform.test.consensus.ConsensusUtils; import com.swirlds.platform.test.consensus.TestIntake; import com.swirlds.platform.test.event.emitter.EventEmitter; import edu.umd.cs.findbugs.annotations.NonNull; @@ -93,13 +91,6 @@ public void restart() { return consensusTestNode; } - public void loadSignedState(@NonNull final SignedState signedState) { - eventEmitter.reset(); - intake.reset(); - ConsensusUtils.loadEventsIntoGenerator(signedState, eventEmitter.getGraphGenerator(), random); - intake.loadFromSignedState(signedState); - } - /** * Adds a number of events from the emitter to the node * diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/framework/ConsensusTestOrchestrator.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/framework/ConsensusTestOrchestrator.java index fae25850d93a..00ad595751a8 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/framework/ConsensusTestOrchestrator.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/main/java/com/swirlds/platform/test/consensus/framework/ConsensusTestOrchestrator.java @@ -16,7 +16,6 @@ package com.swirlds.platform.test.consensus.framework; -import com.swirlds.platform.state.signed.SignedState; import com.swirlds.platform.system.address.AddressBook; import com.swirlds.platform.system.events.EventConstants; import com.swirlds.platform.test.consensus.framework.validation.ConsensusOutputValidation; @@ -60,10 +59,6 @@ public void runGui() { new TestGuiSource(node.getEventEmitter().getGraphGenerator(), node.getIntake()).runGui(); } - public void loadSignedState(final SignedState signedState) { - nodes.forEach(node -> node.loadSignedState(signedState)); - } - /** Generates all events defined in the input */ public ConsensusTestOrchestrator generateAllEvents() { return generateEvents(1d); diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/StateTests.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/StateTests.java index 015233545049..859e8722021b 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/StateTests.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/StateTests.java @@ -25,7 +25,6 @@ import com.swirlds.common.constructable.ConstructableRegistryException; import com.swirlds.common.merkle.crypto.MerkleCryptoFactory; import com.swirlds.common.test.fixtures.io.InputOutputStream; -import com.swirlds.platform.state.DualStateImpl; import com.swirlds.platform.state.State; import com.swirlds.platform.test.fixtures.state.DummySwirldState; import com.swirlds.test.framework.TestComponentTags; @@ -58,7 +57,6 @@ static void setUp() throws ConstructableRegistryException { state = new State(); state.setPlatformState(randomPlatformState()); state.setSwirldState(new DummySwirldState()); - state.setDualState(new DualStateImpl()); state.invalidateHash(); MerkleCryptoFactory.getInstance().digestTreeSync(state); diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/consensus/ConsensusTestDefinitions.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/consensus/ConsensusTestDefinitions.java index ce13aef29e47..84b12be84be1 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/consensus/ConsensusTestDefinitions.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/consensus/ConsensusTestDefinitions.java @@ -22,8 +22,6 @@ import static com.swirlds.platform.test.graph.OtherParentMatrixFactory.createPartitionedOtherParentAffinityMatrix; import static com.swirlds.platform.test.graph.OtherParentMatrixFactory.createShunnedNodeOtherParentAffinityMatrix; -import com.swirlds.common.constructable.ConstructableRegistry; -import com.swirlds.common.constructable.ConstructableRegistryException; import com.swirlds.common.platform.NodeId; import com.swirlds.common.utility.Threshold; import com.swirlds.config.api.ConfigurationBuilder; @@ -32,8 +30,6 @@ import com.swirlds.platform.consensus.ConsensusSnapshot; import com.swirlds.platform.consensus.SyntheticSnapshot; import com.swirlds.platform.internal.EventImpl; -import com.swirlds.platform.state.signed.SignedState; -import com.swirlds.platform.state.signed.SignedStateFileReader; import com.swirlds.platform.test.consensus.framework.ConsensusTestNode; import com.swirlds.platform.test.consensus.framework.ConsensusTestOrchestrator; import com.swirlds.platform.test.consensus.framework.ConsensusTestUtils; @@ -45,19 +41,22 @@ import com.swirlds.platform.test.event.emitter.StandardEventEmitter; import com.swirlds.platform.test.event.source.ForkingEventSource; import com.swirlds.platform.test.fixtures.event.DynamicValue; -import com.swirlds.platform.test.fixtures.event.EventUtils; import com.swirlds.platform.test.fixtures.event.IndexedEvent; import com.swirlds.platform.test.fixtures.event.generator.StandardGraphGenerator; import com.swirlds.platform.test.fixtures.event.source.EventSource; import com.swirlds.platform.test.fixtures.event.source.StandardEventSource; -import com.swirlds.test.framework.ResourceLoader; -import com.swirlds.test.framework.context.TestPlatformContextBuilder; import edu.umd.cs.findbugs.annotations.NonNull; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Path; import java.time.Instant; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Random; +import java.util.Set; +import java.util.Spliterators; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.IntStream; @@ -68,8 +67,7 @@ public final class ConsensusTestDefinitions { private ConsensusTestDefinitions() {} /** - * Changing the order of events (without breaking topological order) should result in the same - * consensus events. + * Changing the order of events (without breaking topological order) should result in the same consensus events. */ public static void orderInvarianceTests(@NonNull final TestInput input) { OrchestratorBuilder.builder() @@ -380,8 +378,7 @@ public static void providesStaleOtherParents(@NonNull final TestInput input) { } /** - * A quorum of nodes stop producing events, thus preventing consensus and round created - * advancement + * A quorum of nodes stop producing events, thus preventing consensus and round created advancement */ public static void quorumOfNodesGoDown(@NonNull final TestInput input) { // Test setup @@ -470,8 +467,7 @@ public static void subQuorumOfNodesGoDown(@NonNull final TestInput input) { } /** - * There should be no problems when the probability of events landing on the same timestamp is - * higher than usual. + * There should be no problems when the probability of events landing on the same timestamp is higher than usual. */ public static void repeatedTimestampTest(@NonNull final TestInput input) { OrchestratorBuilder.builder() @@ -507,8 +503,8 @@ public static void stale(@NonNull final TestInput input) { } /** - * Simulates a consensus restart. The number of nodes and number of events is chosen randomly - * between the supplied bounds + * Simulates a consensus restart. The number of nodes and number of events is chosen randomly between the supplied + * bounds */ public static void restart(@NonNull final TestInput input) { @@ -541,23 +537,6 @@ public static void reconnect(@NonNull final TestInput input) { Validations.standard().ratios(EventRatioValidation.blank().setMinimumConsensusRatio(0.5))); } - public static void migrationTest(@NonNull final TestInput input) - throws URISyntaxException, ConstructableRegistryException, IOException { - ConstructableRegistry.getInstance().registerConstructables("com.swirlds"); - final Path ssPath = ResourceLoader.getFile("modified-mainnet-state.swh.bin"); - final SignedState state = SignedStateFileReader.readSignedStateOnly( - TestPlatformContextBuilder.create().build(), ssPath); - EventUtils.convertEvents(state); - - final ConsensusTestOrchestrator orchestrator = - OrchestratorBuilder.builder().setTestInput(input).build(); - orchestrator.loadSignedState(state); - - orchestrator.generateEvents(1); - orchestrator.validateAndClear( - Validations.standard().ratios(EventRatioValidation.blank().setMinimumConsensusRatio(0.5))); - } - public static void removeNode(@NonNull final TestInput input) { final ConsensusTestOrchestrator orchestrator1 = OrchestratorBuilder.builder().setTestInput(input).build(); diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/consensus/ConsensusTests.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/consensus/ConsensusTests.java index a0ca78c345b5..2d29c8bfd8ff 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/consensus/ConsensusTests.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/consensus/ConsensusTests.java @@ -264,20 +264,6 @@ void fastRestartWithEvents(final ConsensusTestParams params) { .run(); } - @ParameterizedTest - @MethodSource("com.swirlds.platform.test.consensus.ConsensusTestArgs#migrationTestParams") - @Tag(TestTypeTags.FUNCTIONAL) - @Tag(TestComponentTags.PLATFORM) - @Tag(TestComponentTags.CONSENSUS) - @DisplayName("Migration from a state with events to new consensus") - void migrationTest(final ConsensusTestParams params) { - ConsensusTestRunner.create() - .setTest(ConsensusTestDefinitions::migrationTest) - .setParams(params) - .setIterations(NUM_ITER) - .run(); - } - @ParameterizedTest @MethodSource("com.swirlds.platform.test.consensus.ConsensusTestArgs#nodeRemoveTestParams") @Tag(TestTypeTags.FUNCTIONAL) diff --git a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/event/linking/OrphanBufferingLinkerTest.java b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/event/linking/OrphanBufferingLinkerTest.java index 7a7e08ce721e..28759e869a67 100644 --- a/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/event/linking/OrphanBufferingLinkerTest.java +++ b/platform-sdk/swirlds-unit-tests/core/swirlds-platform-test/src/test/java/com/swirlds/platform/test/event/linking/OrphanBufferingLinkerTest.java @@ -29,7 +29,6 @@ import com.swirlds.platform.gossip.IntakeEventCounter; import com.swirlds.platform.gossip.shadowgraph.Generations; import com.swirlds.platform.state.MinGenInfo; -import com.swirlds.platform.state.PlatformData; import com.swirlds.platform.state.PlatformState; import com.swirlds.platform.state.State; import com.swirlds.platform.state.signed.SignedState; @@ -229,13 +228,11 @@ void loadState() { final SignedState signedState = mock(SignedState.class); final State state = mock(State.class); final PlatformState platformState = mock(PlatformState.class); - final PlatformData platformData = mock(PlatformData.class); when(signedState.getState()).thenReturn(state); when(state.getPlatformState()).thenReturn(platformState); - when(platformState.getPlatformData()).thenReturn(platformData); - when(platformData.getRound()).thenReturn(roundGenStart); - when(platformData.getMinGen(Mockito.anyLong())).thenCallRealMethod(); - when(platformData.getMinGenInfo()).thenReturn(minGenInfos); + when(platformState.getRound()).thenReturn(roundGenStart); + when(platformState.getMinGen(Mockito.anyLong())).thenCallRealMethod(); + when(platformState.getMinGenInfo()).thenReturn(minGenInfos); when(signedState.getRound()).thenReturn(roundGenEnd); when(signedState.getMinGenInfo()).thenReturn(minGenInfos); when(signedState.getMinGen(Mockito.anyLong())).thenCallRealMethod();