Hard Audit: don't convert directly from sdk.Int to uint64 (#842)

* refactor away from sdk.Int's .Uint64() method

* refactor cdp module interest calc
This commit is contained in:
Denali Marsh 2021-02-20 17:42:57 +01:00 committed by GitHub
parent 5cd94047a4
commit fe43c2bc41
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 4 deletions

View File

@ -93,9 +93,11 @@ func CalculateInterestFactor(perSecondInterestRate sdk.Dec, secondsElapsed sdk.I
scalingFactorInt := sdk.NewInt(int64(scalingFactor))
// Convert per-second interest rate to a uint scaled by 1e18
interestMantissa := sdk.NewUint(perSecondInterestRate.MulInt(scalingFactorInt).RoundInt().Uint64())
interestMantissa := sdk.NewUintFromBigInt(perSecondInterestRate.MulInt(scalingFactorInt).RoundInt().BigInt())
// Convert seconds elapsed to uint (*not scaled*)
secondsElapsedUint := sdk.NewUint(secondsElapsed.Uint64())
secondsElapsedUint := sdk.NewUintFromBigInt(secondsElapsed.BigInt())
// Calculate the interest factor as a uint scaled by 1e18
interestFactorMantissa := sdk.RelativePow(interestMantissa, secondsElapsedUint, scalingFactorUint)

View File

@ -193,9 +193,9 @@ func CalculateBorrowInterestFactor(perSecondInterestRate sdk.Dec, secondsElapsed
scalingFactorInt := sdk.NewInt(int64(scalingFactor))
// Convert per-second interest rate to a uint scaled by 1e18
interestMantissa := sdk.NewUint(perSecondInterestRate.MulInt(scalingFactorInt).RoundInt().Uint64())
interestMantissa := sdk.NewUintFromBigInt(perSecondInterestRate.MulInt(scalingFactorInt).RoundInt().BigInt())
// Convert seconds elapsed to uint (*not scaled*)
secondsElapsedUint := sdk.NewUint(secondsElapsed.Uint64())
secondsElapsedUint := sdk.NewUintFromBigInt(secondsElapsed.BigInt())
// Calculate the interest factor as a uint scaled by 1e18
interestFactorMantissa := sdk.RelativePow(interestMantissa, secondsElapsedUint, scalingFactorUint)

View File

@ -306,6 +306,22 @@ func (suite *InterestTestSuite) TestCalculateBorrowInterestFactor() {
expectedValue: sdk.MustNewDecFromStr("94702138679846565921082258202543002089.215969366091911769"),
},
},
{
"supports calculated values greater than 1.84x10^19",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("18.5"), // Old uint64 conversion would panic at ~18.45 (1845%/second interest rate)
timeElapsed: sdk.NewInt(30), // Assume a 30 second period, longer than any expected individual block
expectedValue: sdk.MustNewDecFromStr("103550416986452240450480615551792302106.072205164469778538"),
},
},
{
"largest per second interest rate before sdk.Uint overflows 256 bytes",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("23.3"), // 23.4 overflows bit length 256 by 1 byte
timeElapsed: sdk.NewInt(30), // Assume a 30 second period, longer than any expected individual block
expectedValue: sdk.MustNewDecFromStr("104876366068119517411103023062013348034546.437155815200037999"),
},
},
}
for _, tc := range testCases {