Skip to content

Commit

Permalink
completed mint
Browse files Browse the repository at this point in the history
  • Loading branch information
liangping committed May 24, 2024
1 parent 0955b91 commit 3062f2b
Show file tree
Hide file tree
Showing 20 changed files with 477 additions and 121 deletions.
7 changes: 5 additions & 2 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

autocliv1 "cosmossdk.io/api/cosmos/autocli/v1"
reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1"
"github.com/btcsuite/btcd/chaincfg"
dbm "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/log"
Expand Down Expand Up @@ -85,8 +86,8 @@ import (
)

const (
AccountAddressPrefix = "bc"
Name = "side"
// AccountAddressPrefix = "bc"
Name = "side"
)

var Upgrades = []upgrades.Upgrade{v1.Upgrade, v2.Upgrade}
Expand All @@ -102,6 +103,8 @@ var (
// and genesis verification.
ModuleBasics = keepers.AppModuleBasics

BitcoinChainCfg = chaincfg.MainNetParams

// module account permissions
)

Expand Down
1 change: 1 addition & 0 deletions app/keepers/keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ func (appKeepers *AppKeepers) InitNormalKeepers(
appCodec,
appKeepers.keys[btclightclienttypes.StoreKey],
appKeepers.keys[btclightclienttypes.StoreKey],
appKeepers.BankKeeper,
)

// The last arguments can contain custom message handlers, and custom query handlers,
Expand Down
12 changes: 6 additions & 6 deletions cmd/sided/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ import (

func initSDKConfig() {
// Set prefixes
accountPubKeyPrefix := app.AccountAddressPrefix + "pub"
validatorAddressPrefix := app.AccountAddressPrefix + "valoper"
validatorPubKeyPrefix := app.AccountAddressPrefix + "valoperpub"
consNodeAddressPrefix := app.AccountAddressPrefix + "valcons"
consNodePubKeyPrefix := app.AccountAddressPrefix + "valconspub"
accountPubKeyPrefix := app.BitcoinChainCfg.Bech32HRPSegwit + "pub"
validatorAddressPrefix := app.BitcoinChainCfg.Bech32HRPSegwit + "valoper"
validatorPubKeyPrefix := app.BitcoinChainCfg.Bech32HRPSegwit + "valoperpub"
consNodeAddressPrefix := app.BitcoinChainCfg.Bech32HRPSegwit + "valcons"
consNodePubKeyPrefix := app.BitcoinChainCfg.Bech32HRPSegwit + "valconspub"

// Set and seal config
config := sdk.GetConfig()
config.SetBech32PrefixForAccount(app.AccountAddressPrefix, accountPubKeyPrefix)
config.SetBech32PrefixForAccount(app.BitcoinChainCfg.Bech32HRPSegwit, accountPubKeyPrefix)
config.SetBech32PrefixForValidator(validatorAddressPrefix, validatorPubKeyPrefix)
config.SetBech32PrefixForConsensusNode(consNodeAddressPrefix, consNodePubKeyPrefix)

Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ require (
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect
github.com/btcsuite/btcd/btcutil v1.1.5 // indirect
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
github.com/bufbuild/connect-go v1.0.0 // indirect
github.com/bufbuild/protocompile v0.8.0 // indirect
Expand Down Expand Up @@ -215,6 +214,7 @@ require (
github.com/CosmWasm/wasmvm v1.5.2
github.com/Stride-Labs/stride/v16 v16.0.0
github.com/btcsuite/btcd v0.24.1-0.20240318151728-2fc99e0496d2
github.com/btcsuite/btcd/btcutil v1.1.5
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0
github.com/bufbuild/buf v1.7.0
github.com/cosmos/cosmos-proto v1.0.0-beta.4
Expand All @@ -230,8 +230,8 @@ require (
)

replace (
github.com/cosmos/cosmos-sdk => github.com/sideprotocol/cosmos-sdk v0.47.116
// github.com/cosmos/cosmos-sdk => ../cosmos-sdk
// github.com/cosmos/cosmos-sdk => github.com/sideprotocol/cosmos-sdk v0.47.116
github.com/cosmos/cosmos-sdk => ../cosmos-sdk
github.com/cosmos/interchain-security/v3 => github.com/Stride-Labs/interchain-security/v3 v3.1.0-remove-validation-bug-7d3d9d
github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1
github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -973,8 +973,6 @@ github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg
github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8=
github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sideprotocol/cosmos-sdk v0.47.116 h1:9qXEko5qj+RVHR5a01dheCjqzw5MlnYqxu36fqJm5MU=
github.com/sideprotocol/cosmos-sdk v0.47.116/go.mod h1:Ql8d4j8oRXssuNQfVIaa6LRo7VsFMJgSy2Qckd/dcr0=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
Expand Down
16 changes: 14 additions & 2 deletions local_node.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ CHAINID="S2-testnet-1"
MONIKER="Side Labs"
BINARY="$HOME/go/bin/sided"
DENOM_STR="uside,ubtct,uusdc,uusdc.axl,uusdc.noble,uusdt,uusdt.kava,uusdt.axl,uwbtc.axl,uwbtc.osmo,uwbtc"

INITIAL_ACCOUNT_STR="bc1q4h88d5xg2cxxcm2kaej32lx6gkdfrxslfaxm8n"
set -f
IFS=,
DENOMS=($DENOM_STR)
INITIAL_ACCOUNTS=($INITIAL_ACCOUNT_STR)

IFS=";"


INITIAL_SUPPLY="500000000000000"
BLOCK_GAS=10000000
MAX_GAS=10000000000
Expand Down Expand Up @@ -103,6 +103,18 @@ if [[ $overwrite == "y" || $overwrite == "Y" ]]; then
$BINARY add-genesis-account "$KEY" ${BALANCES:1} --keyring-backend $KEYRING --home "$HOMEDIR"
done

# Allocate genesis accounts (cosmos formatted addresses)
for ADDR in "${INITIAL_ACCOUNTS[@]}"; do
BALANCES=""
for key in "${!DENOMS[@]}"; do
BALANCES+=",${INITIAL_SUPPLY}${DENOMS[$key]}"
done
echo ${BALANCES:1}
$BINARY add-genesis-account "$ADDR" ${BALANCES:1} --home "$HOMEDIR"
done



# Sign genesis transaction
echo $INITIAL_SUPPLY${DENOMS[0]}
$BINARY gentx "${KEYS[0]}" $INITIAL_SUPPLY${DENOMS[0]} --keyring-backend $KEYRING --chain-id $CHAINID --identity "666AC57CC678BEC4" --website="https://side.one" --home "$HOMEDIR"
Expand Down
2 changes: 2 additions & 0 deletions proto/side/btclightclient/params.proto
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ message Params {
uint64 max_acceptable_block_depth = 3;
// the denomanation of the voucher
string btc_voucher_denom = 4;
// the address to which the voucher is sent
repeated string btc_voucher_address = 5;
}

// Bitcoin Block Header
Expand Down
9 changes: 7 additions & 2 deletions proto/side/btclightclient/tx.proto
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,13 @@ message MsgSubmitBlockHeadersResponse {
// MsgSubmitTransactionRequest defines the Msg/SubmitTransaction request type.
message MsgSubmitTransactionRequest {
string sender = 1;
string tx = 2;
string proof = 3;
string blockhash = 2;
// the tx bytes in base64 format
// used for parsing the sender of the transaction
string prev_tx_bytes = 3;
// the tx bytes in base64 format
string tx_bytes = 4;
repeated string proof = 5;
}

// MsgSubmitTransactionResponse defines the Msg/SubmitTransaction response type.
Expand Down
6 changes: 4 additions & 2 deletions testutil/keeper/btc_light_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,17 @@ import (
"github.com/cosmos/cosmos-sdk/store"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/sideprotocol/side/app"
"github.com/sideprotocol/side/x/btclightclient/keeper"
"github.com/sideprotocol/side/x/btclightclient/types"
"github.com/stretchr/testify/require"
)

func BtcLightClientKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) {
// app := app.InitSideTestApp(false)
app := app.InitSideTestApp(false)

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

db := tmdb.NewMemDB()
stateStore := store.NewCommitMultiStore(db)
Expand All @@ -35,6 +36,7 @@ func BtcLightClientKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) {
cdc,
storeKey,
memStoreKey,
app.BankKeeper,
)

ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger())
Expand Down
6 changes: 1 addition & 5 deletions x/btclightclient/client/cli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,11 @@ import (
"fmt"
// "strings"

"github.com/sideprotocol/side/x/btclightclient/types"
"github.com/spf13/cobra"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"

// "github.com/cosmos/cosmos-sdk/client/flags"
// sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/sideprotocol/side/x/btclightclient/types"
)

// GetQueryCmd returns the cli query commands for this module
Expand Down
122 changes: 109 additions & 13 deletions x/btclightclient/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ package keeper

import (
"bytes"
"encoding/hex"
"encoding/base64"
"fmt"
"slices"

"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/cosmos-sdk/codec"
Expand All @@ -20,18 +24,23 @@ type (
cdc codec.BinaryCodec
storeKey storetypes.StoreKey
memKey storetypes.StoreKey

bankKeeper types.BankKeeper
}
)

func NewKeeper(
cdc codec.BinaryCodec,
storeKey,
memKey storetypes.StoreKey,

bankKeeper types.BankKeeper,
) *Keeper {
return &Keeper{
cdc: cdc,
storeKey: storeKey,
memKey: memKey,
cdc: cdc,
storeKey: storeKey,
memKey: memKey,
bankKeeper: bankKeeper,
}
}

Expand Down Expand Up @@ -127,13 +136,32 @@ func (k Keeper) SetBlockHeaders(ctx sdk.Context, blockHeader []*types.BlockHeade
return nil
}

// Process Bitcoin Transaction
func (k Keeper) ProcessBitcoinTransaction(ctx sdk.Context, txHexByte, proof string) error {
// Process Bitcoin Deposit Transaction
func (k Keeper) ProcessBitcoinDepositTransaction(ctx sdk.Context, msg *types.MsgSubmitTransactionRequest) error {

ctx.Logger().Debug("Processing Transaction in block: ", msg.Blockhash)

param := k.GetParams(ctx)
header := k.GetBlockHeader(ctx, msg.Blockhash)
// Check if block confirmed
if header == nil {
return types.ErrBlockNotFound
}

best := k.GetBestBlockHeader(ctx)
// Check if the block is confirmed
if best.Height-header.Height < uint64(param.Confirmations) {
return types.ErrNotConfirmed
}
// Check if the block is within the acceptable depth
if best.Height-header.Height > param.MaxAcceptableBlockDepth {
return types.ErrExceedMaxAcceptanceDepth
}

// Decode the hexadecimal transaction
txBytes, err := hex.DecodeString(txHexByte)
// Decode the base64 transaction
txBytes, err := base64.StdEncoding.DecodeString(msg.TxBytes)
if err != nil {
fmt.Println("Error decoding hex:", err)
fmt.Println("Error decoding transaction from base64:", err)
return err
}

Expand All @@ -144,20 +172,88 @@ func (k Keeper) ProcessBitcoinTransaction(ctx sdk.Context, txHexByte, proof stri
fmt.Println("Error deserializing transaction:", err)
return err
}
uTx := btcutil.NewTx(&tx)
if len(uTx.MsgTx().TxIn) < 1 {
return types.ErrInvalidBtcTransaction
}

// Validate the transaction
// cfg := &chaincfg.MainNetParams // Use MainNetParams or TestNet3Params as per your network
if err := blockchain.CheckTransactionSanity(&tx); err != nil {
if err := blockchain.CheckTransactionSanity(uTx); err != nil {
fmt.Println("Transaction is not valid:", err)
return err
}

// extract senders from the previous transaction
prevTxBytes, err := base64.StdEncoding.DecodeString(msg.PrevTxBytes)
if err != nil {
fmt.Println("Error decoding transaction from base64:", err)
return err
}

ctx.Logger().Debug("Processing Transaction", tx)
// Create a new transaction
var prevMsgTx wire.MsgTx
err = prevMsgTx.Deserialize(bytes.NewReader(prevTxBytes))
if err != nil {
fmt.Println("Error deserializing transaction:", err)
return err
}

// transaction.MsgTx().
prevTx := btcutil.NewTx(&prevMsgTx)
if len(prevTx.MsgTx().TxOut) < 1 {
return types.ErrInvalidBtcTransaction
}
// Validate the transaction
if err := blockchain.CheckTransactionSanity(prevTx); err != nil {
fmt.Println("Transaction is not valid:", err)
return err
}

// check if the output is a valid address
// if there are multiple inputs, then the first input is considered as the sender
// assumpe all inputs are from the same sender
out := prevTx.MsgTx().TxOut[tx.TxIn[0].PreviousOutPoint.Index]
// check if the output is a valid address
pk, err := txscript.ParsePkScript(out.PkScript)
if err != nil {
return err
}
sender, err := pk.Address(types.ChainCfg)
if err != nil {
return err
}

// check if the proof is valid
root, err := chainhash.NewHashFromStr(header.MerkleRoot)
if err != nil {
return err
}
if !types.VerifyMerkleProof(msg.Proof, uTx.Hash(), root) {
return types.ErrTransactionNotIncluded
}

for _, out := range uTx.MsgTx().TxOut {
// check if the output is a valid address
pk, err := txscript.ParsePkScript(out.PkScript)
if err != nil {
return err
}
addr, err := pk.Address(types.ChainCfg)
if err != nil {
return err
}

if slices.Contains(param.BtcVoucherAddress, addr.EncodeAddress()) {
// mint the voucher token
coins := sdk.NewCoins(sdk.NewCoin(param.BtcVoucherDenom, sdk.NewInt(int64(out.Value))))
senderAddr, err := sdk.AccAddressFromBech32(sender.EncodeAddress())
if err != nil {
return err
}
k.bankKeeper.MintCoins(ctx, types.ModuleName, coins)
k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, senderAddr, coins)
}

}

return nil
}
Expand Down
6 changes: 3 additions & 3 deletions x/btclightclient/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,18 @@ func (m msgServer) SubmitBlockHeaders(goCtx context.Context, msg *types.MsgSubmi
return &types.MsgSubmitBlockHeadersResponse{}, nil
}

// SubmitBtcTransaction implements types.MsgServer.
// SubmitTransaction implements types.MsgServer.
// No Permission check required for this message
// Since everyone can submit a transaction to mint voucher tokens
// This message is usually sent by relayers
func (m msgServer) SubmitBtcTransaction(goCtx context.Context, msg *types.MsgSubmitTransactionRequest) (*types.MsgSubmitTransactionResponse, error) {
func (m msgServer) SubmitTransaction(goCtx context.Context, msg *types.MsgSubmitTransactionRequest) (*types.MsgSubmitTransactionResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

if err := msg.ValidateBasic(); err != nil {
return nil, err
}

if err := m.ProcessBitcoinTransaction(ctx, msg.Tx, msg.Proof); err != nil {
if err := m.ProcessBitcoinDepositTransaction(ctx, msg); err != nil {
return nil, err
}

Expand Down
Loading

0 comments on commit 3062f2b

Please sign in to comment.