Skip to content

Commit

Permalink
feat: clean deprecated code
Browse files Browse the repository at this point in the history
  • Loading branch information
cosinlink committed Aug 27, 2024
1 parent ed8fbfc commit 34a4be6
Show file tree
Hide file tree
Showing 11 changed files with 58 additions and 2,475 deletions.
205 changes: 1 addition & 204 deletions contracts/BSCValidatorSet.sol
Original file line number Diff line number Diff line change
Expand Up @@ -195,39 +195,7 @@ contract BSCValidatorSet is IBSCValidatorSet, System, IParamSubscriber, IApplica
uint8,
bytes calldata msgBytes
) external override onlyInit onlyCrossChainContract initValidatorExtraSet returns (bytes memory responsePayload) {
(IbcValidatorSetPackage memory validatorSetPackage, bool ok) = decodeValidatorSetSynPackage(msgBytes);
if (!ok) {
return CmnPkg.encodeCommonAckPackage(ERROR_FAIL_DECODE);
}
uint32 resCode;
if (validatorSetPackage.packageType == VALIDATORS_UPDATE_MESSAGE_TYPE) {
resCode = updateValidatorSet(validatorSetPackage.validatorSet, validatorSetPackage.voteAddrs);
} else if (validatorSetPackage.packageType == JAIL_MESSAGE_TYPE) {
if (validatorSetPackage.validatorSet.length != 1) {
emit failReasonWithStr("length of jail validators must be one");
resCode = ERROR_LEN_OF_VAL_MISMATCH;
} else {
address validator = validatorSetPackage.validatorSet[0].consensusAddress;
uint256 index = currentValidatorSetMap[validator];
if (index == 0 || currentValidatorSet[index - 1].jailed) {
emit validatorEmptyJailed(validator);
} else {
// felony will failed if the validator is the only one in the validator set
bool success = _felony(validator, index - 1);
if (!success) {
emit validatorEmptyJailed(validator);
}
}
resCode = CODE_OK;
}
} else {
resCode = ERROR_UNKNOWN_PACKAGE_TYPE;
}
if (resCode == CODE_OK) {
return new bytes(0);
} else {
return CmnPkg.encodeCommonAckPackage(resCode);
}
revert("deprecated");
}

function handleAckPackage(uint8 channelId, bytes calldata msgBytes) external override onlyCrossChainContract {
Expand Down Expand Up @@ -781,177 +749,6 @@ contract BSCValidatorSet is IBSCValidatorSet, System, IParamSubscriber, IApplica
}

/*----------------- Internal Functions -----------------*/
function updateValidatorSet(Validator[] memory validatorSet, bytes[] memory voteAddrs) internal returns (uint32) {
{
// do verify.
if (validatorSet.length > MAX_NUM_OF_VALIDATORS) {
emit failReasonWithStr("the number of validators exceed the limit");
return ERROR_FAIL_CHECK_VALIDATORS;
}
for (uint256 i; i < validatorSet.length; ++i) {
for (uint256 j; j < i; ++j) {
if (validatorSet[i].consensusAddress == validatorSet[j].consensusAddress) {
emit failReasonWithStr("duplicate consensus address of validatorSet");
return ERROR_FAIL_CHECK_VALIDATORS;
}
}
}
}

// step 0: force all maintaining validators to exit `Temporary Maintenance`
// - 1. validators exit maintenance
// - 2. clear all maintainInfo
// - 3. get unjailed validators from validatorSet
Validator[] memory validatorSetTemp;
bytes[] memory voteAddrsTemp;
{
// get migrated validators
Validator[] memory bscValidatorSet = _tmpMigratedValidatorSet;
bytes[] memory bscVoteAddrs = _tmpMigratedVoteAddrs;
for (uint256 i; i < bscValidatorSet.length; ++i) {
bscValidatorSet[i].votingPower = bscValidatorSet[i].votingPower * 3; // amplify the voting power for BSC validators
}
(Validator[] memory mergedValidators, bytes[] memory mergedVoteAddrs) =
_mergeValidatorSet(validatorSet, voteAddrs, bscValidatorSet, bscVoteAddrs);

(validatorSetTemp, voteAddrsTemp) = _forceMaintainingValidatorsExit(mergedValidators, mergedVoteAddrs);
}

{
//step 1: do calculate distribution, do not make it as an internal function for saving gas.
uint256 crossSize;
uint256 directSize;
uint256 validatorsNum = currentValidatorSet.length;
uint8[] memory isMigrated = new uint8[](validatorsNum);
for (uint256 i; i < validatorsNum; ++i) {
if (
IStakeHub(STAKE_HUB_ADDR).consensusToOperator(currentValidatorSet[i].consensusAddress) != address(0)
) {
isMigrated[i] = 1;
if (currentValidatorSet[i].incoming != 0) {
++directSize;
}
} else if (currentValidatorSet[i].incoming >= DUSTY_INCOMING) {
++crossSize;
} else if (currentValidatorSet[i].incoming != 0) {
++directSize;
}
}

//cross transfer
address[] memory crossAddrs = new address[](crossSize);
uint256[] memory crossAmounts = new uint256[](crossSize);
uint256[] memory crossIndexes = new uint256[](crossSize);
address[] memory crossRefundAddrs = new address[](crossSize);
uint256 crossTotal;
// direct transfer
address payable[] memory directAddrs = new address payable[](directSize);
uint256[] memory directAmounts = new uint256[](directSize);
crossSize = 0;
directSize = 0;
uint256 relayFee = ITokenHub(TOKEN_HUB_ADDR).getMiniRelayFee();
if (relayFee > DUSTY_INCOMING) {
emit failReasonWithStr("fee is larger than DUSTY_INCOMING");
return ERROR_RELAYFEE_TOO_LARGE;
}
for (uint256 i; i < validatorsNum; ++i) {
if (isMigrated[i] == 1) {
if (currentValidatorSet[i].incoming != 0) {
directAddrs[directSize] = payable(currentValidatorSet[i].consensusAddress);
directAmounts[directSize] = currentValidatorSet[i].incoming;
isMigrated[directSize] = 1; // directSize must be less than i. so we can use directSize as index
++directSize;
}
} else if (currentValidatorSet[i].incoming >= DUSTY_INCOMING) {
crossAddrs[crossSize] = currentValidatorSet[i].BBCFeeAddress;
uint256 value = currentValidatorSet[i].incoming - currentValidatorSet[i].incoming % PRECISION;
crossAmounts[crossSize] = value.sub(relayFee);
crossRefundAddrs[crossSize] = currentValidatorSet[i].feeAddress;
crossIndexes[crossSize] = i;
crossTotal = crossTotal.add(value);
++crossSize;
} else if (currentValidatorSet[i].incoming != 0) {
directAddrs[directSize] = currentValidatorSet[i].feeAddress;
directAmounts[directSize] = currentValidatorSet[i].incoming;
isMigrated[directSize] = 0;
++directSize;
}
}

//step 2: do cross chain transfer
bool failCross = false;
if (crossTotal > 0) {
try ITokenHub(TOKEN_HUB_ADDR).batchTransferOutBNB{ value: crossTotal }(
crossAddrs, crossAmounts, crossRefundAddrs, uint64(block.timestamp + expireTimeSecondGap)
) returns (bool success) {
if (success) {
emit batchTransfer(crossTotal);
} else {
emit batchTransferFailed(crossTotal, "batch transfer return false");
}
} catch Error(string memory reason) {
failCross = true;
emit batchTransferFailed(crossTotal, reason);
} catch (bytes memory lowLevelData) {
failCross = true;
emit batchTransferLowerFailed(crossTotal, lowLevelData);
}
}

if (failCross) {
for (uint256 i; i < crossIndexes.length; ++i) {
uint256 idx = crossIndexes[i];
bool success = currentValidatorSet[idx].feeAddress.send(currentValidatorSet[idx].incoming);
if (success) {
emit directTransfer(currentValidatorSet[idx].feeAddress, currentValidatorSet[idx].incoming);
} else {
emit directTransferFail(currentValidatorSet[idx].feeAddress, currentValidatorSet[idx].incoming);
}
}
}

// step 3: direct transfer
if (directAddrs.length > 0) {
for (uint256 i; i < directAddrs.length; ++i) {
if (isMigrated[i] == 1) {
IStakeHub(STAKE_HUB_ADDR).distributeReward{ value: directAmounts[i] }(directAddrs[i]);
} else {
bool success = directAddrs[i].send(directAmounts[i]);
if (success) {
emit directTransfer(directAddrs[i], directAmounts[i]);
} else {
emit directTransferFail(directAddrs[i], directAmounts[i]);
}
}
}
}
}

for (uint256 i; i < currentValidatorSet.length; ++i) {
if (currentValidatorSet[i].incoming != 0) {
currentValidatorSet[i].incoming = 0;
}
}

// step 4: do dusk transfer
if (address(this).balance > 0) {
emit systemTransfer(address(this).balance);
address(uint160(SYSTEM_REWARD_ADDR)).transfer(address(this).balance);
}

// step 5: do update validator set state
totalInComing = 0;
numOfJailed = 0;
if (validatorSetTemp.length > 0) {
doUpdateState(validatorSetTemp, voteAddrsTemp);
}

// step 6: clean slash contract
ISlashIndicator(SLASH_CONTRACT_ADDR).clean();
emit validatorSetUpdated();
return CODE_OK;
}

function doUpdateState(Validator[] memory newValidatorSet, bytes[] memory newVoteAddrs) private {
uint256 n = currentValidatorSet.length;
uint256 m = newValidatorSet.length;
Expand Down
38 changes: 3 additions & 35 deletions contracts/GovHub.sol
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,17 @@ contract GovHub is System, IApplication {
uint8,
bytes calldata msgBytes
) external override onlyCrossChainContract returns (bytes memory responsePayload) {
(ParamChangePackage memory proposal, bool success) = decodeSynPackage(msgBytes);
if (!success) {
return CmnPkg.encodeCommonAckPackage(ERROR_FAIL_DECODE);
}
uint32 resCode = notifyUpdates(proposal);
if (resCode == CODE_OK) {
return new bytes(0);
} else {
return CmnPkg.encodeCommonAckPackage(resCode);
}
revert("deprecated");
}

// should not happen
function handleAckPackage(uint8, bytes calldata) external override onlyCrossChainContract {
require(false, "receive unexpected ack package");
revert("deprecated");
}

// should not happen
function handleFailAckPackage(uint8, bytes calldata) external override onlyCrossChainContract {
require(false, "receive unexpected fail ack package");
revert("deprecated");
}

function updateParam(string calldata key, bytes calldata value, address target) external onlyGovernorTimelock {
Expand All @@ -73,27 +64,4 @@ contract GovHub is System, IApplication {
}
return CODE_OK;
}

//rlp encode & decode function
function decodeSynPackage(bytes memory msgBytes) internal pure returns (ParamChangePackage memory, bool) {
ParamChangePackage memory pkg;

RLPDecode.Iterator memory iter = msgBytes.toRLPItem().iterator();
bool success = false;
uint256 idx = 0;
while (iter.hasNext()) {
if (idx == 0) {
pkg.key = string(iter.next().toBytes());
} else if (idx == 1) {
pkg.value = iter.next().toBytes();
} else if (idx == 2) {
pkg.target = iter.next().toAddress();
success = true;
} else {
break;
}
++idx;
}
return (pkg, success);
}
}
13 changes: 3 additions & 10 deletions contracts/SlashIndicator.sol
Original file line number Diff line number Diff line change
Expand Up @@ -94,22 +94,15 @@ contract SlashIndicator is ISlashIndicator, System, IParamSubscriber, IApplicati
uint8,
bytes calldata
) external override onlyCrossChainContract onlyInit returns (bytes memory) {
require(false, "receive unexpected syn package");
revert("deprecated");
}

function handleAckPackage(uint8, bytes calldata msgBytes) external override onlyCrossChainContract onlyInit {
(CmnPkg.CommonAckPackage memory response, bool ok) = CmnPkg.decodeCommonAckPackage(msgBytes);
if (ok) {
emit knownResponse(response.code);
} else {
emit unKnownResponse(response.code);
}
return;
revert("deprecated");
}

function handleFailAckPackage(uint8, bytes calldata) external override onlyCrossChainContract onlyInit {
emit crashResponse();
return;
revert("deprecated");
}

/*----------------- External func -----------------*/
Expand Down
48 changes: 5 additions & 43 deletions contracts/StakeHub.sol
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@ import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./SystemV2.sol";
import "./extension/Protectable.sol";
import "./interface/0.8.x/IBSCValidatorSet.sol";
import "./interface/0.8.x/ICrossChain.sol";
import "./interface/0.8.x/IGovToken.sol";
import "./interface/0.8.x/IStakeCredit.sol";
import "./interface/0.8.x/ITokenHub.sol";
import "./lib/0.8.x/RLPDecode.sol";
import "./lib/0.8.x/Utils.sol";

Expand Down Expand Up @@ -283,45 +281,15 @@ contract StakeHub is SystemV2, Initializable, Protectable {
uint8,
bytes calldata msgBytes
) external onlyCrossChainContract whenNotPaused enableReceivingFund returns (bytes memory) {
(StakeMigrationPackage memory migrationPkg, bool decodeSuccess) = _decodeMigrationSynPackage(msgBytes);
if (!decodeSuccess) revert InvalidSynPackage();

if (migrationPkg.amount == 0) {
return new bytes(0);
}

// claim fund from TokenHub
bool claimSuccess = ITokenHub(TOKEN_HUB_ADDR).claimMigrationFund(migrationPkg.amount);
if (!claimSuccess) {
emit MigrateFailed(
migrationPkg.operatorAddress,
migrationPkg.delegator,
migrationPkg.amount,
StakeMigrationRespCode.CLAIM_FUND_FAILED
);
return msgBytes;
}

StakeMigrationRespCode respCode = _doMigration(migrationPkg);

if (respCode == StakeMigrationRespCode.MIGRATE_SUCCESS) {
return new bytes(0);
} else {
(bool success,) = TOKEN_HUB_ADDR.call{ value: address(this).balance }("");
if (!success) revert TransferFailed();
emit MigrateFailed(migrationPkg.operatorAddress, migrationPkg.delegator, migrationPkg.amount, respCode);
return msgBytes;
}
revert("deprecated");
}

function handleAckPackage(uint8 channelId, bytes calldata msgBytes) external onlyCrossChainContract {
// should not happen
emit UnexpectedPackage(channelId, msgBytes);
revert("deprecated");
}

function handleFailAckPackage(uint8 channelId, bytes calldata msgBytes) external onlyCrossChainContract {
// should not happen
emit UnexpectedPackage(channelId, msgBytes);
revert("deprecated");
}

/*----------------- external functions -----------------*/
Expand Down Expand Up @@ -1181,14 +1149,8 @@ contract StakeHub is SystemV2, Initializable, Protectable {
bool isLast = (numOfJailed >= _validatorSet.length() - 1);
if (isLast) {
// If staking channel is closed, then BC-fusion is finished and we should keep the last eligible validator here
if (
!ICrossChain(CROSS_CHAIN_CONTRACT_ADDR).registeredContractChannelMap(
VALIDATOR_CONTRACT_ADDR, STAKING_CHANNELID
)
) {
emit ValidatorEmptyJailed(valInfo.operatorAddress);
return;
}
emit ValidatorEmptyJailed(valInfo.operatorAddress);
return;
}

if (jailUntil > valInfo.jailUntil) {
Expand Down
Loading

0 comments on commit 34a4be6

Please sign in to comment.