This repository has been archived by the owner on May 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
321 lines (274 loc) · 8.02 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package main
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/rand"
"encoding/hex"
"flag"
"fmt"
"io"
"log"
"net/http"
"encoding/json"
"github.com/c3systems/c3-go/common/c3crypto"
"github.com/c3systems/c3-go/core/chain/mainchain"
"github.com/c3systems/c3-go/core/chain/statechain"
"github.com/c3systems/c3-go/core/p2p/protobuff"
nodetypes "github.com/c3systems/c3-go/node/types"
"github.com/davecgh/go-spew/spew"
"github.com/c3systems/c3-go/common/txparamcoder"
methodTypes "github.com/c3systems/c3-go/core/types/methods"
ipfsaddr "github.com/ipfs/go-ipfs-addr"
csms "github.com/libp2p/go-conn-security-multistream"
lCrypt "github.com/libp2p/go-libp2p-crypto"
host "github.com/libp2p/go-libp2p-host"
peer "github.com/libp2p/go-libp2p-peer"
peerstore "github.com/libp2p/go-libp2p-peerstore"
secio "github.com/libp2p/go-libp2p-secio"
swarm "github.com/libp2p/go-libp2p-swarm"
tptu "github.com/libp2p/go-libp2p-transport-upgrader"
bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
tcp "github.com/libp2p/go-tcp-transport"
ma "github.com/multiformats/go-multiaddr"
msmux "github.com/whyrusleeping/go-smux-multistream"
yamux "github.com/whyrusleeping/go-smux-yamux"
)
var imageHash string
var (
pBuff *protobuff.Node
priv *ecdsa.PrivateKey
pub *ecdsa.PublicKey
pubAddr string
newNode host.Host
peerID peer.ID
)
func getHeadblock() (mainchain.Block, error) {
return mainchain.Block{}, nil
}
func broadcastTx(tx *statechain.Transaction) (*nodetypes.SendTxResponse, error) {
return nil, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
// note: second field is header
file, _, err := r.FormFile("file")
if err != nil {
fmt.Printf("err getting file %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
defer file.Close()
// name := strings.Split(header.Filename, ".")
// fmt.Printf("File name %s\n", name[0])
// Copy the file data to my buffer
if _, err = io.Copy(&buf, file); err != nil {
fmt.Printf("err copying %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
payload := txparamcoder.ToJSONArray(
txparamcoder.EncodeMethodName("processImage"),
txparamcoder.EncodeParam(hex.EncodeToString(buf.Bytes())),
txparamcoder.EncodeParam("jpg"), // TODO: read this from the filename...
)
tx := statechain.NewTransaction(&statechain.TransactionProps{
ImageHash: imageHash,
Method: methodTypes.InvokeMethod,
Payload: payload,
From: pubAddr,
})
if err = tx.SetSig(priv); err != nil {
fmt.Printf("error setting sig\n%v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
if err = tx.SetHash(); err != nil {
fmt.Printf("error setting hash\n%v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
if tx.Props().TxHash == nil {
fmt.Print("tx hash is nil!")
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
txBytes, err := tx.Serialize()
if err != nil {
fmt.Printf("error getting tx bytes\n%v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
go func() {
ch := make(chan interface{})
if err := pBuff.ProcessTransaction.SendTransaction(peerID, txBytes, ch); err != nil {
fmt.Printf("err processing tx\n%v", err)
return
}
res := <-ch
fmt.Printf("received response on channel %v", res)
}()
txhash := *tx.Props().TxHash
outputStruct := struct{
TxHash string `json:"txHash"`
}{
TxHash: txhash,
}
output, err := json.Marshal(outputStruct)
if err != nil {
fmt.Print("marshal response error")
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
if _, err = fmt.Fprint(w, string(output)); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
}
func main() {
log.Println("building node")
imageHashFlag := flag.String("image", "", "Image hash")
shouldSendGenesisBlock := flag.Bool("genesis", false, "send genesis block")
peer := flag.String("peer", "", "peer multiaddr")
flag.Parse()
imageHash = *imageHashFlag
if err := buildNode(*peer); err != nil {
log.Fatalf("err building node\n%v", err)
}
if *shouldSendGenesisBlock {
log.Println("sending genesis block")
if err := sendGenesisBlock(); err != nil {
log.Fatalf("err sending genesis block\n%v", err)
}
}
http.HandleFunc("/submit", handler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./index.html")
})
log.Println("listening on :8000")
log.Fatal(http.ListenAndServe(":8000", nil))
}
// note: https://github.com/libp2p/go-libp2p-swarm/blob/da01184afe4c67bec58c5e73f3350ad80b624c0d/testing/testing.go#L39
func genUpgrader(n *swarm.Swarm) *tptu.Upgrader {
id := n.LocalPeer()
pk := n.Peerstore().PrivKey(id)
secMuxer := new(csms.SSMuxer)
secMuxer.AddTransport(secio.ID, &secio.Transport{
LocalID: id,
PrivateKey: pk,
})
stMuxer := msmux.NewBlankTransport()
stMuxer.AddTransport("/yamux/1.0.0", yamux.DefaultTransport)
return &tptu.Upgrader{
Secure: secMuxer,
Muxer: stMuxer,
Filters: n.Filters,
}
}
func sendGenesisBlock() error {
ch := make(chan interface{})
tx := statechain.NewTransaction(&statechain.TransactionProps{
ImageHash: imageHash,
Method: methodTypes.Deploy,
Payload: nil,
From: pubAddr,
})
if err := tx.SetHash(); err != nil {
return err
}
if err := tx.SetSig(priv); err != nil {
return err
}
txBytes, err := tx.Serialize()
if err != nil {
return err
}
if err := pBuff.ProcessTransaction.SendTransaction(peerID, txBytes, ch); err != nil {
return err
}
v := <-ch
switch v.(type) {
case error:
err, _ := v.(error)
return err
default:
spew.Dump(v)
return nil
}
}
func buildNode(peerStr string) error {
wPriv, wPub, err := lCrypt.GenerateKeyPairWithReader(lCrypt.RSA, 4096, rand.Reader)
if err != nil {
fmt.Printf("err generating keypairs %v", err)
return err
}
pid, err := peer.IDFromPublicKey(wPub)
if err != nil {
fmt.Printf("err getting pid %v", err)
return err
}
uri := "/ip4/0.0.0.0/tcp/9008"
listen, err := ma.NewMultiaddr(uri)
if err != nil {
fmt.Printf("err listening %v", err)
return err
}
ps := peerstore.NewPeerstore()
if err = ps.AddPrivKey(pid, wPriv); err != nil {
fmt.Printf("err adding priv key %v", err)
return err
}
if err = ps.AddPubKey(pid, wPub); err != nil {
fmt.Printf("err adding pub key %v", err)
return err
}
swarmNet := swarm.NewSwarm(context.Background(), pid, ps, nil)
tcpTransport := tcp.NewTCPTransport(genUpgrader(swarmNet))
if err = swarmNet.AddTransport(tcpTransport); err != nil {
fmt.Printf("err adding transport %v", err)
return err
}
if err = swarmNet.AddListenAddr(listen); err != nil {
fmt.Printf("err adding listenaddr %v", err)
return err
}
newNode = bhost.New(swarmNet)
addr, err := ipfsaddr.ParseString(peerStr)
if err != nil {
fmt.Printf("err parsing peer string %v", err)
return err
}
pinfo, err := peerstore.InfoFromP2pAddr(addr.Multiaddr())
if err != nil {
fmt.Printf("err getting pinfo %v", err)
return err
}
log.Println("[node] FULL", addr.String())
log.Println("[node] PIN INFO", pinfo)
if err = newNode.Connect(context.Background(), *pinfo); err != nil {
fmt.Printf("err connecting to peer; %v\n", err)
return err
}
peerID = pinfo.ID
newNode.Peerstore().AddAddrs(pinfo.ID, pinfo.Addrs, peerstore.PermanentAddrTTL)
pBuff, err = protobuff.NewNode(&protobuff.Props{
Host: newNode,
GetHeadBlockFN: getHeadblock,
BroadcastTransactionFN: broadcastTx,
})
if err != nil {
fmt.Printf("error starting protobuff node\n%v", err)
return err
}
priv, pub, err = c3crypto.NewKeyPair()
if err != nil {
fmt.Printf("error getting keypair\n%v", err)
return err
}
pubAddr, err = c3crypto.EncodeAddress(pub)
if err != nil {
fmt.Printf("error getting addr\n%v", err)
return err
}
return nil
}