Skip to content

Commit

Permalink
Merge pull request #601 from bnb-chain/develop
Browse files Browse the repository at this point in the history
feat: code clean up
  • Loading branch information
cosinlink authored Oct 9, 2024
2 parents 5d12307 + e0792c7 commit d156409
Show file tree
Hide file tree
Showing 35 changed files with 722 additions and 5,692 deletions.
63 changes: 63 additions & 0 deletions .github/workflows/check-bsc-hardfork-bytecode.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
name: Compare genesis with bytecode files from BSC repo
on:
push:
branches:
- master
- develop
pull_request:
types: [opened, edited, synchronize]
branches:
- master
- develop
permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues` option.
# pull-requests: read
jobs:
main:
runs-on: ubuntu-latest
if: contains(github.event.pull_request.body, '>CI')
steps:
- uses: actions/checkout@master
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
# - name: Run your CI script
# run: echo ${{github.event.pull_request.title}}

- name: Install Project Dependencies
run: |
npm install ts-node -g
npm install
- name: Extract BSC commitId and hardfork name from PR description
uses: actions/github-script@v6
id: extract_pr_description
with:
script: |
const prBody = context.payload.pull_request.body || '';
console.log("PR description:", prBody);
const p1 = prBody.indexOf('>CI')
const p2 = prBody.indexOf('>CI', p1 + 1)
if (p1 < 0 || p2 < 0) {
throw new Error('PR description does not contain >CI tag');
}
const info = JSON.parse(prBody.substring(p1 + 3, p2))
console.log('info', info, info.hardfork, info.bsc)
core.setOutput('hardfork', info.hardfork)
core.setOutput('bsc', info.bsc)
- name: Compare genesis with hardfork bytecode files from BSC repo
run: |
export HARDFORK=${{ steps.extract_pr_description.outputs.hardfork }}
export BSC_URL=${{ steps.extract_pr_description.outputs.bsc }}
ts-node scripts/check-bsc-hardfork-bytecode.ts
399 changes: 33 additions & 366 deletions contracts/BSCValidatorSet.sol

Large diffs are not rendered by default.

49 changes: 4 additions & 45 deletions contracts/GovHub.sol
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
pragma solidity 0.6.4;

import "./System.sol";
import "./lib/0.6.x/BytesToTypes.sol";
import "./lib/0.6.x/Memory.sol";
import "./lib/0.6.x/BytesLib.sol";
import "./interface/0.6.x/IParamSubscriber.sol";
import "./interface/0.6.x/IApplication.sol";
import "./lib/0.6.x/RLPDecode.sol";
import "./lib/0.6.x/CmnPkg.sol";

contract GovHub is System, IApplication {
using RLPDecode for *;

uint8 public constant PARAM_UPDATE_MESSAGE_TYPE = 0;

uint32 public constant ERROR_TARGET_NOT_CONTRACT = 101;
uint32 public constant ERROR_TARGET_CONTRACT_FAIL = 102;

event failReasonWithStr(string message);
event failReasonWithBytes(bytes message);
event paramChange(string key, bytes value);
event paramChange(string key, bytes value); // @dev deprecated

struct ParamChangePackage {
string key;
Expand All @@ -31,26 +22,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 +55,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);
}
}
4 changes: 3 additions & 1 deletion contracts/GovToken.sol
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ contract GovToken is
_delegate(delegator, delegatee);
}

function burn(uint256) public pure override {
function burn(
uint256
) public pure override {
revert BurnNotAllowed();
}

Expand Down
55 changes: 11 additions & 44 deletions contracts/SlashIndicator.sol
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@ import "./interface/0.6.x/ISlashIndicator.sol";
import "./interface/0.6.x/IApplication.sol";
import "./interface/0.6.x/IBSCValidatorSet.sol";
import "./interface/0.6.x/IParamSubscriber.sol";
import "./interface/0.6.x/ICrossChain.sol";
import "./interface/0.6.x/ISystemReward.sol";
import "./interface/0.6.x/IStakeHub.sol";
import "./lib/0.6.x/CmnPkg.sol";
import "./lib/0.6.x/RLPEncode.sol";

contract SlashIndicator is ISlashIndicator, System, IParamSubscriber, IApplication {
Expand Down Expand Up @@ -46,16 +44,15 @@ contract SlashIndicator is ISlashIndicator, System, IParamSubscriber, IApplicati
uint256 public felonySlashScope;

event validatorSlashed(address indexed validator);
event maliciousVoteSlashed(bytes32 indexed voteAddrSlice);
event indicatorCleaned();
event paramChange(string key, bytes value);

event knownResponse(uint32 code);
event unKnownResponse(uint32 code);
event crashResponse();

event failedFelony(address indexed validator, uint256 slashCount, bytes failReason);

event maliciousVoteSlashed(bytes32 indexed voteAddrSlice); // @dev deprecated
event knownResponse(uint32 code); // @dev deprecated
event unKnownResponse(uint32 code); // @dev deprecated
event crashResponse(); // @dev deprecated

struct Indicator {
uint256 height;
uint256 count;
Expand Down Expand Up @@ -94,22 +91,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 All @@ -134,16 +124,7 @@ contract SlashIndicator is ISlashIndicator, System, IParamSubscriber, IApplicati
if (indicator.count % felonyThreshold == 0) {
indicator.count = 0;
IBSCValidatorSet(VALIDATOR_CONTRACT_ADDR).felony(validator);
if (IStakeHub(STAKE_HUB_ADDR).consensusToOperator(validator) != address(0)) {
_downtimeSlash(validator, indicator.count, false);
} else {
// send slash msg to bc if validator is not migrated
try ICrossChain(CROSS_CHAIN_CONTRACT_ADDR).sendSynPackage(
SLASH_CHANNELID, encodeSlashPackage(validator), 0
) { } catch (bytes memory reason) {
emit failedFelony(validator, indicator.count, reason);
}
}
_downtimeSlash(validator, indicator.count, false);
} else if (indicator.count % misdemeanorThreshold == 0) {
IBSCValidatorSet(VALIDATOR_CONTRACT_ADDR).misdemeanor(validator);
}
Expand Down Expand Up @@ -272,7 +253,6 @@ contract SlashIndicator is ISlashIndicator, System, IParamSubscriber, IApplicati
);

// reward sender and felony validator if validator found
// TODO: after BC-fusion, we don't need to check if validator is living
(address[] memory vals, bytes[] memory voteAddrs) =
IBSCValidatorSet(VALIDATOR_CONTRACT_ADDR).getLivingValidators();
for (uint256 i; i < voteAddrs.length; ++i) {
Expand All @@ -284,17 +264,7 @@ contract SlashIndicator is ISlashIndicator, System, IParamSubscriber, IApplicati
}
}

if (IStakeHub(STAKE_HUB_ADDR).voteToOperator(_evidence.voteAddr) != address(0)) {
IStakeHub(STAKE_HUB_ADDR).maliciousVoteSlash(_evidence.voteAddr);
} else {
// send slash msg to bc if the validator not migrated
ICrossChain(CROSS_CHAIN_CONTRACT_ADDR).sendSynPackage(
SLASH_CHANNELID, encodeVoteSlashPackage(_evidence.voteAddr), 0
);

bytes32 voteAddrSlice = BytesLib.toBytes32(_evidence.voteAddr, 0);
emit maliciousVoteSlashed(voteAddrSlice);
}
IStakeHub(STAKE_HUB_ADDR).maliciousVoteSlash(_evidence.voteAddr);
}

function submitDoubleSignEvidence(bytes memory header1, bytes memory header2) public onlyInit {
Expand Down Expand Up @@ -343,10 +313,7 @@ contract SlashIndicator is ISlashIndicator, System, IParamSubscriber, IApplicati
* @param validator Who will be jailed
*/
function sendFelonyPackage(address validator) external override(ISlashIndicator) onlyValidatorContract onlyInit {
try ICrossChain(CROSS_CHAIN_CONTRACT_ADDR).sendSynPackage(SLASH_CHANNELID, encodeSlashPackage(validator), 0) { }
catch (bytes memory reason) {
emit failedFelony(validator, 0, reason);
}
emit failedFelony(validator, 0, "deprecated");
}

function _verifyBLSSignature(VoteData memory vote, bytes memory voteAddr) internal view returns (bool) {
Expand Down
44 changes: 33 additions & 11 deletions contracts/StakeCredit.sol
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ contract StakeCredit is SystemV2, Initializable, ReentrancyGuardUpgradeable, ERC
* @param delegator the address of the delegator
* @return shares the amount of shares minted
*/
function delegate(address delegator) external payable onlyStakeHub returns (uint256 shares) {
function delegate(
address delegator
) external payable onlyStakeHub returns (uint256 shares) {
if (msg.value == 0) revert ZeroAmount();
shares = _mintAndSync(delegator, msg.value);
if (shares == 0) revert ZeroShares();
Expand Down Expand Up @@ -181,7 +183,9 @@ contract StakeCredit is SystemV2, Initializable, ReentrancyGuardUpgradeable, ERC
* @dev Distribute the reward to the validator and all delegators. Only the `StakeHub` contract can call this function.
* @param commissionRate the commission rate of the validator
*/
function distributeReward(uint64 commissionRate) external payable onlyStakeHub {
function distributeReward(
uint64 commissionRate
) external payable onlyStakeHub {
uint256 bnbAmount = msg.value;
uint256 _commission = (bnbAmount * uint256(commissionRate)) / COMMISSION_RATE_BASE;
uint256 _reward = bnbAmount - _commission;
Expand All @@ -202,7 +206,9 @@ contract StakeCredit is SystemV2, Initializable, ReentrancyGuardUpgradeable, ERC
* @param slashBnbAmount the amount of BNB to be slashed
* @return realSlashBnbAmount the real amount of BNB slashed
*/
function slash(uint256 slashBnbAmount) external onlyStakeHub returns (uint256) {
function slash(
uint256 slashBnbAmount
) external onlyStakeHub returns (uint256) {
uint256 selfDelegation = balanceOf(validator);
uint256 slashShares = getSharesByPooledBNB(slashBnbAmount);

Expand All @@ -219,15 +225,19 @@ contract StakeCredit is SystemV2, Initializable, ReentrancyGuardUpgradeable, ERC
/**
* @return the amount of shares that corresponds to `_bnbAmount` protocol-controlled BNB.
*/
function getSharesByPooledBNB(uint256 bnbAmount) public view returns (uint256) {
function getSharesByPooledBNB(
uint256 bnbAmount
) public view returns (uint256) {
if (totalPooledBNB == 0) revert ZeroTotalPooledBNB();
return (bnbAmount * totalSupply()) / totalPooledBNB;
}

/**
* @return the amount of BNB that corresponds to `_sharesAmount` token shares.
*/
function getPooledBNBByShares(uint256 shares) public view returns (uint256) {
function getPooledBNBByShares(
uint256 shares
) public view returns (uint256) {
if (totalSupply() == 0) revert ZeroTotalShares();
return (shares * totalPooledBNB) / totalSupply();
}
Expand All @@ -243,14 +253,18 @@ contract StakeCredit is SystemV2, Initializable, ReentrancyGuardUpgradeable, ERC
/**
* @return the total length of delegator's pending unbond queue.
*/
function pendingUnbondRequest(address delegator) public view returns (uint256) {
function pendingUnbondRequest(
address delegator
) public view returns (uint256) {
return _unbondRequestsQueue[delegator].length();
}

/**
* @return the total number of delegator's claimable unbond requests.
*/
function claimableUnbondRequest(address delegator) public view returns (uint256) {
function claimableUnbondRequest(
address delegator
) public view returns (uint256) {
uint256 length = _unbondRequestsQueue[delegator].length();
uint256 count;
for (uint256 i; i < length; ++i) {
Expand Down Expand Up @@ -290,19 +304,25 @@ contract StakeCredit is SystemV2, Initializable, ReentrancyGuardUpgradeable, ERC
/**
* @return the personal unbond sequence of the delegator.
*/
function unbondSequence(address delegator) public view returns (uint256) {
function unbondSequence(
address delegator
) public view returns (uint256) {
return _unbondSequence[delegator].current();
}

/**
* @return the total amount of BNB staked and reward of the delegator.
*/
function getPooledBNB(address account) public view returns (uint256) {
function getPooledBNB(
address account
) public view returns (uint256) {
return getPooledBNBByShares(balanceOf(account));
}

/*----------------- internal functions -----------------*/
function _bootstrapInitialHolder(uint256 initAmount) internal onlyInitializing {
function _bootstrapInitialHolder(
uint256 initAmount
) internal onlyInitializing {
// check before mint
uint256 toLock = IStakeHub(STAKE_HUB_ADDR).LOCK_AMOUNT();
if (initAmount <= toLock || validator == address(0) || totalSupply() != 0) revert WrongInitContext();
Expand Down Expand Up @@ -330,7 +350,9 @@ contract StakeCredit is SystemV2, Initializable, ReentrancyGuardUpgradeable, ERC
totalPooledBNB -= bnbAmount;
}

function _useSequence(address delegator) internal returns (uint256 current) {
function _useSequence(
address delegator
) internal returns (uint256 current) {
CountersUpgradeable.Counter storage sequence = _unbondSequence[delegator];
current = sequence.current();
sequence.increment();
Expand Down
Loading

0 comments on commit d156409

Please sign in to comment.