Skip to content

Commit

Permalink
feat: address from public key function (#673)
Browse files Browse the repository at this point in the history
  • Loading branch information
robdefeo committed Feb 14, 2021
1 parent d4b88c6 commit 32a4ba6
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
29 changes: 29 additions & 0 deletions internal/protocols/algorand/address.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package algorand

import (
"crypto/sha512"

"github.com/mailchain/mailchain/crypto"
"github.com/mailchain/mailchain/crypto/ed25519"
"github.com/pkg/errors"
)

const (
checksumLength = 4
)

// Address returns the address from the public key.
func Address(pubKey crypto.PublicKey) ([]byte, error) {
switch pubKey.(type) {
case ed25519.PublicKey, *ed25519.PublicKey:
return append(pubKey.Bytes(), checksum(pubKey.Bytes())...), nil
default:
return nil, errors.Errorf("invalid public key type: %T", pubKey)
}
}

// Algorand 4-byte checksum added to public key to make an algorand address.
func checksum(data []byte) []byte {
fullHash := sha512.Sum512_256(data)
return fullHash[len(fullHash)-checksumLength:]
}
69 changes: 69 additions & 0 deletions internal/protocols/algorand/address_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package algorand

import (
"testing"

"github.com/mailchain/mailchain/crypto"
"github.com/mailchain/mailchain/crypto/ed25519/ed25519test"
"github.com/mailchain/mailchain/crypto/secp256k1/secp256k1test"
"github.com/mailchain/mailchain/crypto/sr25519/sr25519test"
"github.com/stretchr/testify/assert"
)

func TestAddress(t *testing.T) {
type args struct {
pubKey crypto.PublicKey
}
tests := []struct {
name string
args args
want []byte
wantErr bool
}{
{
"sofia",
args{
ed25519test.SofiaPublicKey,
},
[]byte{0x72, 0x3c, 0xaa, 0x23, 0xa5, 0xb5, 0x11, 0xaf, 0x5a, 0xd7, 0xb7, 0xef, 0x60, 0x76, 0xe4, 0x14, 0xab, 0x7e, 0x75, 0xa9, 0xdc, 0x91, 0xe, 0xa6, 0xe, 0x41, 0x7a, 0x2b, 0x77, 0xa, 0x56, 0x71, 0x64, 0xea, 0x58, 0x50},
false,
},
{
"charlotte",
args{
ed25519test.CharlottePublicKey,
},
[]byte{0x2e, 0x32, 0x2f, 0x87, 0x40, 0xc6, 0x1, 0x72, 0x11, 0x1a, 0xc8, 0xea, 0xdc, 0xdd, 0xa2, 0x51, 0x2f, 0x90, 0xd0, 0x6d, 0xe, 0x50, 0x3e, 0xf1, 0x89, 0x97, 0x9a, 0x15, 0x9b, 0xec, 0xe1, 0xe8, 0x96, 0xc8, 0xe9, 0x2c},
false,
},
{
"err-secp256k1",
args{
secp256k1test.CharlottePublicKey,
},
nil,
true,
},
{
"err-sr25519",
args{
sr25519test.SofiaPublicKey,
},
nil,
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Address(tt.args.pubKey)
if (err != nil) != tt.wantErr {
t.Errorf("Address() error = %v, wantErr %v", err, tt.wantErr)
return
}

if !assert.Equal(t, tt.want, got) {
t.Errorf("Address() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 32a4ba6

Please sign in to comment.