Skip to content

Commit

Permalink
Merge pull request #93 from keithsue/sufay/fix-signature-verify
Browse files Browse the repository at this point in the history
Fix signature verification
  • Loading branch information
liangping authored Jun 24, 2024
2 parents 0f3e6e6 + 0a0a7f8 commit a59b345
Show file tree
Hide file tree
Showing 13 changed files with 69 additions and 49 deletions.
2 changes: 1 addition & 1 deletion testutil/keeper/btc_light_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func BtcLightClientKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) {
app := app.InitSideTestApp(false)

storeKey := sdk.NewKVStoreKey(types.StoreKey)
memStoreKey := storetypes.NewMemoryStoreKey(types.ModuleName)
memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey)

db := tmdb.NewMemDB()
stateStore := store.NewCommitMultiStore(db)
Expand Down
8 changes: 4 additions & 4 deletions x/btcbridge/client/cli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,10 +174,10 @@ func CmdQueryUTXOs() *cobra.Command {
}

if len(args) == 0 {
return queryUTXOs(&clientCtx, cmd.Context())
return queryUTXOs(cmd.Context(), &clientCtx)
}

return queryUTXOsByAddr(&clientCtx, cmd.Context(), args[0])
return queryUTXOsByAddr(cmd.Context(), &clientCtx, args[0])
},
}

Expand All @@ -186,7 +186,7 @@ func CmdQueryUTXOs() *cobra.Command {
return cmd
}

func queryUTXOs(clientCtx *client.Context, cmdCtx context.Context) error {
func queryUTXOs(cmdCtx context.Context, clientCtx *client.Context) error {
queryClient := types.NewQueryClient(clientCtx)

res, err := queryClient.QueryUTXOs(cmdCtx, &types.QueryUTXOsRequest{})
Expand All @@ -197,7 +197,7 @@ func queryUTXOs(clientCtx *client.Context, cmdCtx context.Context) error {
return clientCtx.PrintProto(res)
}

func queryUTXOsByAddr(clientCtx *client.Context, cmdCtx context.Context, addr string) error {
func queryUTXOsByAddr(cmdCtx context.Context, clientCtx *client.Context, addr string) error {
queryClient := types.NewQueryClient(clientCtx)

_, err := sdk.AccAddressFromBech32(addr)
Expand Down
5 changes: 4 additions & 1 deletion x/btcbridge/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState)
k.SetParams(ctx, genState.Params)
k.SetBestBlockHeader(ctx, genState.BestBlockHeader)
if len(genState.BlockHeaders) > 0 {
k.SetBlockHeaders(ctx, genState.BlockHeaders)
err := k.SetBlockHeaders(ctx, genState.BlockHeaders)
if err != nil {
panic(err)
}
}
// import utxos
for _, utxo := range genState.Utxos {
Expand Down
10 changes: 10 additions & 0 deletions x/btcbridge/keeper/keeper_deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,16 @@ func (k Keeper) mintBTC(ctx sdk.Context, uTx *btcutil.Tx, height uint64, sender
}

func (k Keeper) mintRUNE(ctx sdk.Context, uTx *btcutil.Tx, height uint64, sender string, vault *types.Vault, out *wire.TxOut, vout int, denom string) {
// TODO

_ = ctx
_ = uTx
_ = height
_ = sender
_ = vault
_ = out
_ = vout
_ = denom
}

func (k Keeper) existsInHistory(ctx sdk.Context, txHash string) bool {
Expand Down
4 changes: 2 additions & 2 deletions x/btcbridge/keeper/keeper_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func (k Keeper) NewSigningRequest(ctx sdk.Context, sender string, coin sdk.Coin,
}

// lock the selected utxos
k.LockUTXOs(ctx, selectedUTXOs)
_ = k.LockUTXOs(ctx, selectedUTXOs)

// save the change utxo and mark minted
if changeUTXO != nil {
Expand Down Expand Up @@ -230,7 +230,7 @@ func (k Keeper) spendUTXOs(ctx sdk.Context, uTx *btcutil.Tx) {
vout := in.PreviousOutPoint.Index

if k.IsUTXOLocked(ctx, hash, uint64(vout)) {
k.SpendUTXO(ctx, hash, uint64(vout))
_ = k.SpendUTXO(ctx, hash, uint64(vout))
}
}
}
3 changes: 1 addition & 2 deletions x/btcbridge/keeper/utxo.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ func (bvk *BaseUTXOViewKeeper) IterateAllUTXOs(ctx sdk.Context, cb func(utxo *ty
func (bvk *BaseUTXOViewKeeper) IterateUTXOsByAddr(ctx sdk.Context, addr string, cb func(addr string, utxo *types.UTXO) (stop bool)) {
store := ctx.KVStore(bvk.storeKey)

keyPrefix := append(types.BtcOwnerUtxoKeyPrefix, []byte(addr)...)
iterator := sdk.KVStorePrefixIterator(store, keyPrefix)
iterator := sdk.KVStorePrefixIterator(store, append(types.BtcOwnerUtxoKeyPrefix, []byte(addr)...))
defer iterator.Close()

for ; iterator.Valid(); iterator.Next() {
Expand Down
31 changes: 17 additions & 14 deletions x/btcbridge/types/bitcoin_transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ const (

// default minimum relay fee
MinRelayFee = 1000

// default hash type for signature
SigHashType = txscript.SigHashAll
)

// BuildPsbt builds a bitcoin psbt from the given params.
Expand Down Expand Up @@ -131,18 +134,18 @@ func AddUTXOsToTx(tx *wire.MsgTx, utxos []*UTXO, outAmount int64, changeOut *wir
}

return selectedUTXOs, nil
} else {
tx.TxOut = tx.TxOut[0 : len(tx.TxOut)-1]
}

if changeValue == 0 {
return selectedUTXOs, nil
}
tx.TxOut = tx.TxOut[0 : len(tx.TxOut)-1]

if changeValue < 0 {
feeWithoutChange := GetTxVirtualSize(tx, selectedUTXOs) * feeRate
if inputAmount-outAmount-feeWithoutChange >= 0 {
return selectedUTXOs, nil
}
if changeValue == 0 {
return selectedUTXOs, nil
}

if changeValue < 0 {
feeWithoutChange := GetTxVirtualSize(tx, selectedUTXOs) * feeRate
if inputAmount-outAmount-feeWithoutChange >= 0 {
return selectedUTXOs, nil
}
}
}
Expand All @@ -161,17 +164,17 @@ func GetTxVirtualSize(tx *wire.MsgTx, utxos []*UTXO) int64 {

switch txscript.GetScriptClass(utxos[i].PubKeyScript) {
case txscript.WitnessV1TaprootTy:
dummyWitness = make([]byte, 64)
dummyWitness = make([]byte, 65)

case txscript.WitnessV0PubKeyHashTy:
dummyWitness = make([]byte, 72+33)
dummyWitness = make([]byte, 73+33)

case txscript.ScriptHashTy:
dummySigScript = make([]byte, 1+1+1+20)
dummyWitness = make([]byte, 72+33)
dummyWitness = make([]byte, 73+33)

case txscript.PubKeyHashTy:
dummySigScript = make([]byte, 1+72+1+33)
dummySigScript = make([]byte, 1+73+1+33)

default:
}
Expand Down
9 changes: 6 additions & 3 deletions x/btcbridge/types/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ const (

// RouterKey defines the module's message routing key
RouterKey = ModuleName

// MemStoreKey defines the in-memory store key
MemStoreKey = "mem_btcbridge"
)

func KeyPrefix(p string) []byte {
Expand Down Expand Up @@ -47,10 +50,10 @@ func BtcUtxoKey(hash string, vout uint64) []byte {
}

func BtcOwnerUtxoKey(owner string, hash string, vout uint64) []byte {
key := append(BtcOwnerUtxoKeyPrefix, []byte(owner)...)
key = append(key, []byte(hash)...)
key := append(append(BtcOwnerUtxoKeyPrefix, []byte(owner)...), []byte(hash)...)
key = append(key, Int64ToBytes(vout)...)

return append(key, Int64ToBytes(vout)...)
return key
}

func BtcBlockHeaderHashKey(hash string) []byte {
Expand Down
27 changes: 16 additions & 11 deletions x/btcbridge/types/signature.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,14 @@ import (
)

// VerifyPsbtSignatures verifies the signatures of the given psbt
// Note: assume that the psbt is valid and all inputs are native segwit
// Note: assume that the psbt is finalized and all inputs are native segwit
func VerifyPsbtSignatures(p *psbt.Packet) bool {
// extract signed tx
signedTx, err := psbt.Extract(p)
if err != nil {
return false
}

// build previous output fetcher
prevOutputFetcher := txscript.NewMultiPrevOutFetcher(nil)

Expand All @@ -25,32 +31,31 @@ func VerifyPsbtSignatures(p *psbt.Packet) bool {
// verify signatures
for i := range p.Inputs {
output := p.Inputs[i].WitnessUtxo
hashType := p.Inputs[i].SighashType

witness := p.Inputs[i].FinalScriptWitness
if len(witness) < 72+33 {
witness := signedTx.TxIn[i].Witness
if len(witness) != 2 {
return false
}

sigBytes := witness[0 : len(witness)-33]
pkBytes := witness[len(witness)-33:]
sigBytes := witness[0]
pkBytes := witness[1]

if sigBytes[len(sigBytes)-1] != byte(hashType) {
sig, err := ecdsa.ParseDERSignature(sigBytes)
if err != nil {
return false
}

sig, err := ecdsa.ParseDERSignature(sigBytes[0 : len(sigBytes)-1])
pk, err := secp256k1.ParsePubKey(pkBytes)
if err != nil {
return false
}

pk, err := secp256k1.ParsePubKey(pkBytes)
if err != nil {
if sigBytes[len(sigBytes)-1] != byte(SigHashType) {
return false
}

sigHash, err := txscript.CalcWitnessSigHash(output.PkScript, txscript.NewTxSigHashes(p.UnsignedTx, prevOutputFetcher),
hashType, p.UnsignedTx, i, output.Value)
SigHashType, p.UnsignedTx, i, output.Value)
if err != nil {
return false
}
Expand Down
2 changes: 1 addition & 1 deletion x/gmm/keeper/pool_apr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func TestAPRCalculation(t *testing.T) {

// Calculate the APR for the pool
apr := keeper.GetAPR(ctx, pool.PoolId)
expectedAPR := sdk.NewCoin("usdt", sdkmath.NewInt(6600000))
expectedAPR := sdk.NewCoin("usdt", sdkmath.NewInt(6500000))
// Assert APR calculation
require.Equal(t, expectedAPR.Amount.LTE(apr[0].Amount), true, "Calculated APR does not match expected APR")
}
9 changes: 3 additions & 6 deletions x/gmm/types/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func (p *Pool) DecreaseShare(amt sdkmath.Int) {
// IncreaseLiquidity adds xx amount liquidity to assets in pool
func (p *Pool) IncreaseLiquidity(coins []sdk.Coin) error {
for _, coin := range coins {
asset, index, exists := p.GetAssetByDenom(coin.Denom) //Assets[coin.Denom]
asset, index, exists := p.GetAssetByDenom(coin.Denom) // Assets[coin.Denom]
if !exists {
return ErrNotFoundAssetInPool
}
Expand Down Expand Up @@ -131,12 +131,9 @@ func (p *Pool) findAssetByDenom(denom string) (PoolAsset, error) {
func (p *Pool) GetAssetList() []PoolAsset {
assets := make([]PoolAsset, 0)
if p != nil {
for _, asset := range p.Assets {
assets = append(assets, asset)
}
return assets
assets = append(assets, p.Assets...)
}
return nil
return assets
}

func (p *Pool) GetTokens() []sdk.Coin {
Expand Down
2 changes: 1 addition & 1 deletion x/gmm/types/poolI.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
)

func (p *PoolI) ToPool() Pool {
assets := []PoolAsset{} //make(map[PoolAsset])
assets := []PoolAsset{} // make(map[PoolAsset])
for _, asset := range p.Assets {
weight := sdkmath.NewIntFromUint64(uint64(asset.Weight))
assets = append(assets, PoolAsset{
Expand Down
6 changes: 3 additions & 3 deletions x/gmm/types/pool_weight.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ func (p *Pool) estimateShareWithSingleLiquidityInWeightPool(coin sdk.Coin) (sdk.
decAsset := sdk.NewDecCoinFromCoin(asset.Token)
weight := sdk.NewDecFromInt(*asset.Weight).Quo(sdk.NewDec(100)) // divide by 100
ratio := decToken.Amount.Quo(decAsset.Amount).Add(sdk.NewDec(1))
precision := big.NewInt(1) //sdk.MustNewDecFromStr("0.00000001")
precision := big.NewInt(1) // sdk.MustNewDecFromStr("0.00000001")
_ = weight
_ = ratio
_ = precision
factor := sdk.NewInt(1)
//factor := (ApproximatePow(ratio.BigInt(), weight.BigInt(), precision).Sub(sdk.OneDec()))
// factor := (ApproximatePow(ratio.BigInt(), weight.BigInt(), precision).Sub(sdk.OneDec()))
issueAmount := p.TotalShares.Amount.Mul(factor).Quo(sdk.NewInt(1e10))
outputToken := sdk.Coin{
Amount: issueAmount,
Expand Down Expand Up @@ -105,7 +105,7 @@ func (p *Pool) estimateSwapInWeightPool(amountIn sdk.Coin, denomOut string) (sdk
ratio := balanceIn.Quo(balanceInPlusAmount)
oneMinusRatio := sdk.NewDec(1).Sub(ratio)
power := weightIn.Quo(weightOut)
precision := "0.00000001" //sdk.MustNewDecFromStr("0.00000001")
precision := "0.00000001" // sdk.MustNewDecFromStr("0.00000001")
factor, err := ApproximatePow(oneMinusRatio.String(), power.String(), precision) // 100 iterations for example
if err != nil {
return sdk.Coin{}, err
Expand Down

0 comments on commit a59b345

Please sign in to comment.