OSDN Git Service

add getAddress
authorChengcheng Zhang <943420582@qq.com>
Sun, 8 Sep 2019 14:29:10 +0000 (22:29 +0800)
committerChengcheng Zhang <943420582@qq.com>
Sun, 8 Sep 2019 14:29:10 +0000 (22:29 +0800)
swap/htlc.go
swap/htlc_test.go

index 048dc15..ababa2c 100644 (file)
@@ -1,14 +1,19 @@
 package swap
 
 import (
+       "encoding/hex"
        "errors"
        "fmt"
        "strconv"
        "strings"
+
+       "github.com/bytom/crypto"
+       "github.com/bytom/protocol/vm/vmutil"
 )
 
 var (
        errFailedGetSignData = errors.New("Failed to get sign data")
+       errFailedGetAddress  = errors.New("Failed to get address by account ID")
 )
 
 type HTLCAccount struct {
@@ -238,6 +243,36 @@ func listAddresses(accountID string) ([]AddressInfo, error) {
        return *res, nil
 }
 
+func getAddress(accountID, contractControlProgram string) (string, error) {
+       publicKey, err := getRecipientPublicKey(contractControlProgram)
+       if err != nil {
+               return "", err
+       }
+
+       publicKeyBytes, err := hex.DecodeString(publicKey)
+       if err != nil {
+               return "", err
+       }
+
+       publicKeyHash := crypto.Ripemd160(publicKeyBytes)
+       controlProgram, err := vmutil.P2WPKHProgram(publicKeyHash)
+       if err != nil {
+               return "", err
+       }
+
+       addressInfos, err := listAddresses(accountID)
+       if err != nil {
+               return "", err
+       }
+
+       for _, addressInfo := range addressInfos {
+               if addressInfo.ControlProgram == hex.EncodeToString(controlProgram) {
+                       return addressInfo.Address, nil
+               }
+       }
+       return "", errFailedGetAddress
+}
+
 type signUnlockHTLCContractTransactionRequest struct {
        Password    string                                     `json:"password"`
        Transaction buildUnlockHTLCContractTransactionResponse `json:"transaction"`
index 3f3c271..c08d11c 100644 (file)
@@ -66,10 +66,14 @@ func TestBuildUnlockHTLCContractTransaction(t *testing.T) {
 
 func TestListAddresses(t *testing.T) {
        accountID := "10CJPO1HG0A02"
-       addresses, err := listAddresses(accountID)
+       addressInfos, err := listAddresses(accountID)
        if err != nil {
                fmt.Println(err)
        }
-       fmt.Println(addresses[0].AccountAlias)
-       fmt.Println(addresses[0].Address)
+       controlProgram := "00145b0a81adc5c2d68a9967082a09c96e82d62aa058"
+       for _, addressInfo := range addressInfos {
+               if addressInfo.ControlProgram == controlProgram {
+                       fmt.Println("address:", addressInfo.Address)
+               }
+       }
 }