Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(common)!: bitcoin address validation to verify networks #1364

Merged
merged 2 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions common/address_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//go:build TESTNET
brewmaster012 marked this conversation as resolved.
Show resolved Hide resolved
// +build TESTNET

package common

import (
Expand Down
5 changes: 4 additions & 1 deletion common/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,13 @@ func (chain Chain) EncodeAddress(b []byte) (string, error) {
if err != nil {
return "", err
}
_, err = btcutil.DecodeAddress(addrStr, chainParams)
addr, err := btcutil.DecodeAddress(addrStr, chainParams)
if err != nil {
return "", err
}
if !addr.IsForNet(chainParams) {
return "", fmt.Errorf("address is not for network %s", chainParams.Name)
}
return addrStr, nil
}
return "", fmt.Errorf("chain (%d) not supported", chain.ChainId)
Expand Down
55 changes: 55 additions & 0 deletions common/chain_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package common

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestChain_EncodeAddress(t *testing.T) {
type fields struct {
ChainName ChainName
ChainId int32
}

tests := []struct {
name string
chain Chain
b []byte
want string
wantErr bool
}{
{
name: "should error if b is not a valid address on the network",
chain: Chain{
ChainName: ChainName_btc_testnet,
ChainId: 18332,
},
b: []byte("bc1qk0cc73p8m7hswn8y2q080xa4e5pxapnqgp7h9c"),
want: "",
wantErr: true,
},
{
name: "should pass if b is a valid address on the network",
chain: Chain{
ChainName: ChainName_btc_mainnet,
ChainId: 8332,
},
b: []byte("bc1qk0cc73p8m7hswn8y2q080xa4e5pxapnqgp7h9c"),
want: "bc1qk0cc73p8m7hswn8y2q080xa4e5pxapnqgp7h9c",
wantErr: false,
},
}

for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
s, err := tc.chain.EncodeAddress(tc.b)
if tc.wantErr {
require.Error(t, err)
return
}
require.Equal(t, tc.want, s)
})
}
}
Loading