forked from holochain/holochain-proto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbs.go
85 lines (76 loc) · 2 KB
/
bs.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
// Copyright (C) 2013-2017, The MetaCurrency Project (Eric Harris-Braun, Arthur Brock, et. al.)
// Use of this source code is governed by GPLv3 found in the LICENSE file
//----------------------------------------------------------------------------------------
// implements bootstrap server access
package holochain
import (
"bytes"
"encoding/json"
"fmt"
peer "github.com/libp2p/go-libp2p-peer"
pstore "github.com/libp2p/go-libp2p-peerstore"
ma "github.com/multiformats/go-multiaddr"
"io/ioutil"
"net/http"
)
type BSReq struct {
Version int
NodeID string
NodeAddr string
}
type BSResp struct {
Req BSReq
Remote string
}
func (h *Holochain) BSpost() (err error) {
nodeID := peer.IDB58Encode(h.node.HashAddr)
req := BSReq{Version: 1, NodeID: nodeID, NodeAddr: h.node.NetAddr.String()}
host := h.config.BootstrapServer
id, _ := h.ID()
url := fmt.Sprintf("http://%s/%s/%s", host, id.String(), nodeID)
var b []byte
b, err = json.Marshal(req)
//var resp *http.Response
if err == nil {
_, err = http.Post(url, "application/json", bytes.NewBuffer(b))
}
return
}
func (h *Holochain) BSget() (err error) {
host := h.config.BootstrapServer
if host == "" {
return
}
id, _ := h.ID()
url := fmt.Sprintf("http://%s/%s", host, id.String())
var resp *http.Response
resp, err = http.Get(url)
if err == nil {
defer resp.Body.Close()
var b []byte
b, err = ioutil.ReadAll(resp.Body)
//log.Infof("bs responded with:%s", string(b))
if err == nil {
var nodes []BSResp
err = json.Unmarshal(b, &nodes)
if err == nil {
myNodeID := peer.IDB58Encode(h.node.HashAddr)
for _, r := range nodes {
var id peer.ID
var addr ma.Multiaddr
id, err = peer.IDB58Decode(r.Req.NodeID)
if err == nil {
addr, err = ma.NewMultiaddr(r.Req.NodeAddr)
if err == nil {
if myNodeID != r.Req.NodeID {
log.Infof("discovered peer: %s", r.Req.NodeID)
h.node.Host.Peerstore().AddAddr(id, addr, pstore.PermanentAddrTTL)
}
}
}
}
}
}
}
return
}