Skip to content

Commit

Permalink
Add cache staking block template in the chainholder
Browse files Browse the repository at this point in the history
  • Loading branch information
AionJayT committed Apr 22, 2020
1 parent 37dceef commit 6c7ef06
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions modApiServer/src/org/aion/api/server/rpc3/AionChainHolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.aion.zero.impl.types.BlockContext;
import org.aion.zero.impl.types.StakingBlock;
import org.aion.zero.impl.valid.FutureBlockRule;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;

public class AionChainHolder implements ChainHolder {
Expand All @@ -41,6 +42,9 @@ public class AionChainHolder implements ChainHolder {
private final FutureBlockRule futureBlockRule;
private final Logger logger;
private final ScheduledExecutorService blockSubmitExecutor;
private final AtomicReference<Pair<Long, StakingBlock>> stakingBlockTemplate;
private final static long templateRefreshRate = 2000; //ms


public AionChainHolder(IAionChain chain,
AccountManagerInterface accountManager) {
Expand All @@ -58,6 +62,7 @@ public AionChainHolder(IAionChain chain,
this.futureBlockRule = new FutureBlockRule();
logger = AionLoggerFactory.getLogger(LogEnum.CONS.name());
blockSubmitExecutor = Executors.newSingleThreadScheduledExecutor();
stakingBlockTemplate = new AtomicReference<>(null);
}

@Override
Expand Down Expand Up @@ -149,12 +154,23 @@ void scheduleTask(StakingBlock stakingBlock, long period) {
public byte[] submitSeed(byte[] newSeed, byte[] signingPublicKey, byte[] coinBase) {
if (!isUnityForkEnabled()) throw new UnsupportedOperationException();
else {
StakingBlock blockTemplate =
this.chain.getStakingBlockTemplate(newSeed, signingPublicKey, coinBase);
if (blockTemplate == null) {
return ByteUtil.EMPTY_BYTE_ARRAY;
} else {
Pair<Long, StakingBlock> template = stakingBlockTemplate.get();
StakingBlock blockTemplate = template == null ? null : template.getRight();
if (blockTemplate != null
&& Arrays.equals(blockTemplate.getSeed(), newSeed)
&& Arrays.equals(blockTemplate.getHeader().getSigningPublicKey(), signingPublicKey)
&& blockTemplate.getCoinbase().equals(new AionAddress(coinBase))
&& System.currentTimeMillis() <= template.getLeft() + templateRefreshRate) {
return blockTemplate.getHeader().getMineHash();
} else {
blockTemplate = this.chain.getStakingBlockTemplate(newSeed, signingPublicKey, coinBase);
stakingBlockTemplate.set(Pair.of(System.currentTimeMillis(), blockTemplate));

if (blockTemplate == null) {
return ByteUtil.EMPTY_BYTE_ARRAY;
} else {
return blockTemplate.getHeader().getMineHash();
}
}
}
}
Expand Down

0 comments on commit 6c7ef06

Please sign in to comment.