Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bb 158 relayer btc support init connection between shard of multisig wallet #2

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,24 @@ The following chains are supported:
## How to use ?

Refer to the [WIKI](<https://github.com/icon-project/centralized-relay/wiki>).

## Bitcoin Relay

How to run Slave server

### Prerequisites

Go 1.x installed
Set up your environment variables as required

### Start Slave

```bash
GO_ENV=master MASTER_SERVER=http://localhost:8080 SLAVE_SERVER=http://localhost:8081 API_KEY=your_api_key go run main.go bitcoin
```

### Start Master

```bash
GO_ENV=slave MASTER_SERVER=http://localhost:8080 SLAVE_SERVER=http://localhost:8081 API_KEY=your_api_key go run main.go bitcoin
```
18 changes: 18 additions & 0 deletions cmd/bitcoin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package cmd

import (
"github.com/icon-project/centralized-relay/relayer/chains/bitcoin"
"github.com/spf13/cobra"
)

func bitcoinCmd(a *appState) *cobra.Command {
bitcoinCmd := &cobra.Command{
Use: "bitcoin",
Short: "Run Bitcoin Relayer",
Run: func(cmd *cobra.Command, args []string) {
bitcoin.RunApp()
},
}

return bitcoinCmd
}
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ func NewRootCmd(log *zap.Logger) *cobra.Command {
dbCmd(a),
keystoreCmd(a),
contractCMD(a),
bitcoinCmd(a),
)
return rootCmd
}
Expand Down
927 changes: 927 additions & 0 deletions go.work.sum

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions relayer/chains/bitcoin/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package bitcoin

import (
"os"
)

func RunApp() {
goEnv := os.Getenv("GO_ENV")
if goEnv == "master" {
startMaster()
} else {
startSlave()
}
}
114 changes: 114 additions & 0 deletions relayer/chains/bitcoin/master.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package bitcoin

import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"sync"
)

func startMaster() {
go callSlaves()
http.HandleFunc("/execute", handleExecute)
server := &http.Server{
Addr: "8080",
Handler: nil,
}

log.Printf("Master starting on port %s", "8080")
log.Fatal(server.ListenAndServe())
}

func handleExecute(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}

apiKey := r.Header.Get("x-api-key")
if apiKey == "" {
http.Error(w, "Missing API Key", http.StatusUnauthorized)
return
}
apiKeyHeader := os.Getenv("API_KEY")
if apiKey != apiKeyHeader {
http.Error(w, "Invalid API Key", http.StatusForbidden)
return
}

var msg string

body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()

err = json.Unmarshal(body, &msg)
if err != nil {
http.Error(w, "Failed to parse JSON", http.StatusBadRequest)
return
}

// Process the message as needed
fmt.Printf("Received message: %v\n", msg)

// Send a response
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
response := map[string]string{"status": "success", "msg": msg}
fmt.Println(response)
json.NewEncoder(w).Encode(response)
}

func callSlaves() {
fmt.Printf("Master request slave")
slavePort := os.Getenv("SLAVE_SERVER")

// Call slave to get more data
var wg sync.WaitGroup
responses := make(chan string, 2)

wg.Add(1)
go requestPartialSign(slavePort, responses, &wg)

go func() {
wg.Wait()
close(responses)
}()

for res := range responses {
fmt.Println("Received response from slave:", res)
}
}

func requestPartialSign(url string, responses chan<- string, wg *sync.WaitGroup) {
defer wg.Done()

client := &http.Client{}
apiKeyHeader := os.Getenv("API_KEY")

req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatalf("Failed to create request: %v", err)
}

req.Header.Add("x-api-key", apiKeyHeader)

resp, err := client.Do(req)

if err != nil {
log.Fatalf("Failed to send request: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading response: %v", err)
}

responses <- string(body)
}
36 changes: 36 additions & 0 deletions relayer/chains/bitcoin/slave.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package bitcoin

import (
"log"
"net/http"
"os"
)

func startSlave() {
http.HandleFunc("/", handleRoot)
server := &http.Server{
Addr: "8080",
Handler: nil,
}

log.Printf("Slave starting on port %s", "8080")
log.Fatal(server.ListenAndServe())
}

func handleRoot(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
apiKey := r.Header.Get("x-api-key")
if apiKey == "" {
http.Error(w, "Missing API Key", http.StatusUnauthorized)
return
}
apiKeyHeader := os.Getenv("API_KEY")
if apiKey != apiKeyHeader {
http.Error(w, "Invalid API Key", http.StatusForbidden)
return
}
w.Write([]byte("hello world"))
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
6 changes: 5 additions & 1 deletion relayer/chains/evm/event_parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/icon-project/centralized-relay/relayer/transmission"
providerTypes "github.com/icon-project/centralized-relay/relayer/types"
)

Expand All @@ -13,7 +14,10 @@ func (p *Provider) getRelayMessageFromLog(log types.Log) (*providerTypes.Message
return nil, fmt.Errorf("topic length mismatch")
}
topic := log.Topics[0]

// TODO: Bitcoin
if len(topic) != 0 {
transmission.CallBitcoinRelay(topic.Hex())
}
switch topic {
case crypto.Keccak256Hash([]byte(EmitMessage)):
msg, err := p.client.ParseConnectionMessage(log)
Expand Down
6 changes: 5 additions & 1 deletion relayer/chains/icon/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"

"github.com/icon-project/centralized-relay/relayer/chains/icon/types"
"github.com/icon-project/centralized-relay/relayer/transmission"
providerTypes "github.com/icon-project/centralized-relay/relayer/types"
"go.uber.org/zap"
)
Expand Down Expand Up @@ -86,7 +87,10 @@ func (p *Provider) GenerateMessages(ctx context.Context, key *providerTypes.Mess
if err != nil {
return nil, fmt.Errorf("GenerateMessage:GetTransactionResult %v", err)
}

// TODO: Bitcoin
if err == nil {
transmission.CallBitcoinRelay(string(txResult.BlockHeight))
}
for _, el := range txResult.EventLogs {
var (
dst string
Expand Down
38 changes: 38 additions & 0 deletions relayer/transmission/transmission.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package transmission

import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
)

func CallBitcoinRelay(message string) []byte {
fmt.Printf("Call Bitcoin Relayer")
masterServer := os.Getenv("MASTER_SERVER")

client := &http.Client{}
apiKeyHeader := os.Getenv("API_KEY")

req, err := http.NewRequest("POST", masterServer+"/execute", bytes.NewBuffer([]byte(message)))
if err != nil {
log.Fatalf("Failed to create request: %v", err)
}

req.Header.Add("x-api-key", apiKeyHeader)
req.Header.Set("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
log.Fatalf("Failed to send request: %v", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading response: %v", err)
}
return body
}