github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/ethclient/privateTransactionManagerClient.go (about)

     1  package ethclient
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/base64"
     6  	"encoding/json"
     7  	"fmt"
     8  	"net/http"
     9  	"net/url"
    10  
    11  	"github.com/kisexp/xdchain/common"
    12  )
    13  
    14  type privateTransactionManagerClient interface {
    15  	StoreRaw(data []byte, privateFrom string) (common.EncryptedPayloadHash, error)
    16  }
    17  
    18  type privateTransactionManagerDefaultClient struct {
    19  	rawurl     string
    20  	httpClient *http.Client
    21  }
    22  
    23  // Create a new client to interact with private transaction manager via a HTTP endpoint
    24  func newPrivateTransactionManagerClient(endpoint string) (privateTransactionManagerClient, error) {
    25  	_, err := url.Parse(endpoint)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	return &privateTransactionManagerDefaultClient{
    30  		rawurl:     endpoint,
    31  		httpClient: &http.Client{},
    32  	}, nil
    33  }
    34  
    35  type storeRawReq struct {
    36  	Payload string `json:"payload"`
    37  	From    string `json:"from,omitempty"`
    38  }
    39  
    40  type storeRawResp struct {
    41  	Key string `json:"key"`
    42  }
    43  
    44  func (pc *privateTransactionManagerDefaultClient) StoreRaw(data []byte, privateFrom string) (common.EncryptedPayloadHash, error) {
    45  	storeRawReq := &storeRawReq{
    46  		Payload: base64.StdEncoding.EncodeToString(data),
    47  		From:    privateFrom,
    48  	}
    49  	reqBodyBuf := new(bytes.Buffer)
    50  	if err := json.NewEncoder(reqBodyBuf).Encode(storeRawReq); err != nil {
    51  		return common.EncryptedPayloadHash{}, err
    52  	}
    53  	resp, err := pc.httpClient.Post(pc.rawurl+"/storeraw", "application/json", reqBodyBuf)
    54  	if err != nil {
    55  		return common.EncryptedPayloadHash{}, fmt.Errorf("unable to invoke /storeraw due to %s", err)
    56  	}
    57  	defer func() {
    58  		_ = resp.Body.Close()
    59  	}()
    60  	if resp.StatusCode != http.StatusOK {
    61  		return common.EncryptedPayloadHash{}, fmt.Errorf("server returns %s", resp.Status)
    62  	}
    63  	// parse response
    64  	var storeRawResp storeRawResp
    65  	if err := json.NewDecoder(resp.Body).Decode(&storeRawResp); err != nil {
    66  		return common.EncryptedPayloadHash{}, err
    67  	}
    68  	encryptedPayloadHash, err := common.Base64ToEncryptedPayloadHash(storeRawResp.Key)
    69  	if err != nil {
    70  		return common.EncryptedPayloadHash{}, err
    71  	}
    72  	return encryptedPayloadHash, nil
    73  }