github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/private/engine/constellation/node.go (about) 1 package constellation 2 3 import ( 4 "bytes" 5 "encoding/base64" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 "strings" 10 11 "github.com/kisexp/xdchain/common" 12 ) 13 14 type Client struct { 15 httpClient *http.Client 16 } 17 18 func (c *Client) SendPayload(pl []byte, b64From string, b64To []string, acHashes common.EncryptedPayloadHashes, acMerkleRoot common.Hash) (common.EncryptedPayloadHash, error) { 19 method := "POST" 20 url := "http+unix://c/sendraw" 21 buf := bytes.NewBuffer(pl) 22 req, err := http.NewRequest(method, url, buf) 23 if err != nil { 24 return common.EncryptedPayloadHash{}, fmt.Errorf("unable to build request for (method:%s,path:%s). Cause: %v", method, url, err) 25 } 26 if b64From != "" { 27 req.Header.Set("c11n-from", b64From) 28 } 29 req.Header.Set("c11n-to", strings.Join(b64To, ",")) 30 req.Header.Set("Content-Type", "application/octet-stream") 31 res, err := c.httpClient.Do(req) 32 33 if res != nil { 34 defer res.Body.Close() 35 } 36 if err != nil { 37 return common.EncryptedPayloadHash{}, fmt.Errorf("unable to submit request (method:%s,path:%s). Cause: %v", method, url, err) 38 } 39 if res.StatusCode != 200 { 40 return common.EncryptedPayloadHash{}, fmt.Errorf("Non-200 status code: %+v", res) 41 } 42 43 hashBytes, err := ioutil.ReadAll(base64.NewDecoder(base64.StdEncoding, res.Body)) 44 if err != nil { 45 return common.EncryptedPayloadHash{}, fmt.Errorf("unable to decode response body for (method:%s,path:%s). Cause: %v", method, url, err) 46 } 47 return common.BytesToEncryptedPayloadHash(hashBytes), nil 48 } 49 50 func (c *Client) ReceivePayload(key common.EncryptedPayloadHash) ([]byte, common.EncryptedPayloadHashes, common.Hash, error) { 51 method := "GET" 52 url := "http+unix://c/receiveraw" 53 req, err := http.NewRequest(method, url, nil) 54 if err != nil { 55 return nil, nil, common.Hash{}, fmt.Errorf("unable to build request for (method:%s,url:%s). Cause: %v", method, url, err) 56 } 57 req.Header.Set("c11n-key", key.ToBase64()) 58 res, err := c.httpClient.Do(req) 59 if err != nil { 60 return nil, nil, common.Hash{}, fmt.Errorf("unable to submit request (method:%s,url:%s). Cause: %v", method, url, err) 61 } 62 defer res.Body.Close() 63 64 if res.StatusCode == 404 { // payload not found 65 return nil, nil, common.Hash{}, nil // empty payload 66 } 67 if res.StatusCode != 200 { 68 return nil, nil, common.Hash{}, fmt.Errorf("Non-200 status code: %+v", res) 69 } 70 71 payload, err := ioutil.ReadAll(res.Body) 72 if err != nil { 73 return nil, nil, common.Hash{}, fmt.Errorf("unable to read response body for (method:%s,path:%s). Cause: %v", method, url, err) 74 } 75 76 return payload, nil, common.Hash{}, nil 77 }