/
main.go
96 lines (79 loc) · 1.85 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"context"
"crypto/ed25519"
"encoding/hex"
"encoding/json"
"github.com/xssnick/tonutils-go/adnl"
"github.com/xssnick/tonutils-go/adnl/dht"
rldphttp "github.com/xssnick/tonutils-go/adnl/rldp/http"
"io"
"log"
"net"
"net/http"
"os"
)
func handler(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write([]byte("Hello, " + request.URL.Query().Get("name") +
"\nThis TON site works natively using tonutils-go!"))
}
func main() {
_, priv, err := ed25519.GenerateKey(nil)
if err != nil {
panic(err)
}
gateway := adnl.NewGateway(priv)
err = gateway.StartClient()
if err != nil {
panic(err)
}
dhtClient, err := dht.NewClientFromConfigUrl(context.Background(), gateway, "https://ton-blockchain.github.io/testnet-global.config.json")
if err != nil {
panic(err)
}
mx := http.NewServeMux()
mx.HandleFunc("/hello", handler)
s := rldphttp.NewServer(loadKey(), dhtClient, mx)
addr, err := rldphttp.SerializeADNLAddress(s.Address())
if err != nil {
panic(err)
}
log.Println("Listening on", addr+".adnl")
s.SetExternalIP(net.ParseIP(getPublicIP()))
if err = s.ListenAndServe(":9056"); err != nil {
panic(err)
}
}
func getPublicIP() string {
req, err := http.Get("http://ip-api.com/json/")
if err != nil {
return err.Error()
}
defer req.Body.Close()
body, err := io.ReadAll(req.Body)
if err != nil {
return err.Error()
}
var ip struct {
Query string
}
_ = json.Unmarshal(body, &ip)
return ip.Query
}
func loadKey() ed25519.PrivateKey {
file := "./key.txt"
data, err := os.ReadFile(file)
if err != nil {
_, srvKey, err := ed25519.GenerateKey(nil)
if err != nil {
panic(err)
}
err = os.WriteFile(file, []byte(hex.EncodeToString(srvKey.Seed())), 555)
if err != nil {
panic(err)
}
return srvKey
}
dec, err := hex.DecodeString(string(data))
return ed25519.NewKeyFromSeed(dec)
}