Skip to content

Commit

Permalink
feat(address): improved NewAddress to support both bech32/base58 (#760)
Browse files Browse the repository at this point in the history
Signed-off-by: Ales Verbic <[email protected]>
  • Loading branch information
verbotenj authored Oct 15, 2024
1 parent d5143a0 commit ee4c98b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
27 changes: 19 additions & 8 deletions ledger/common/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package common

import (
"fmt"
"strings"

"github.com/blinklabs-io/gouroboros/base58"
"github.com/blinklabs-io/gouroboros/bech32"
Expand Down Expand Up @@ -53,15 +54,25 @@ type Address struct {
extraData []byte
}

// NewAddress returns an Address based on the provided bech32 address string
// NewAddress returns an Address based on the provided bech32/base58 address string
// It detects if the string has mixed case assumes it is a base58 encoded address
// otherwise, it assumes it is bech32 encoded
func NewAddress(addr string) (Address, error) {
_, data, err := bech32.DecodeNoLimit(addr)
if err != nil {
return Address{}, err
}
decoded, err := bech32.ConvertBits(data, 5, 8, false)
if err != nil {
return Address{}, err
var decoded []byte
var err error

if strings.ToLower(addr) != addr {
// Mixed case detected: Assume Base58 encoding (e.g., Byron addresses)
decoded = base58.Decode(addr)
} else {
_, data, err := bech32.DecodeNoLimit(addr)
if err != nil {
return Address{}, err
}
decoded, err = bech32.ConvertBits(data, 5, 8, false)
if err != nil {
return Address{}, err
}
}
a := Address{}
err = a.populateFromBytes(decoded)
Expand Down
9 changes: 9 additions & 0 deletions ledger/common/address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"testing"

"github.com/blinklabs-io/gouroboros/internal/test"
"github.com/stretchr/testify/assert"
)

func TestAddressFromBytes(t *testing.T) {
Expand Down Expand Up @@ -225,3 +226,11 @@ func TestAddressStakeAddress(t *testing.T) {
}
}
}

func TestAddressPaymentAddress_MixedCase(t *testing.T) {
// address with mixed case Byron address
mixedCaseAddress := "Ae2tdPwUPEYwFx4dmJheyNPPYXtvHbJLeCaA96o6Y2iiUL18cAt7AizN2zG"
addr, err := NewAddress(mixedCaseAddress)
assert.Nil(t, err, "Expected no error when decoding a mixed-case address")
assert.NotNil(t, addr, "Expected a valid address object after decoding")
}

0 comments on commit ee4c98b

Please sign in to comment.