-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
172 lines (142 loc) · 4.55 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
package main
import (
"blockchain-proyecto/files"
"bufio"
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
net "github.com/libp2p/go-libp2p/core/network"
peer "github.com/libp2p/go-libp2p/core/peer"
pstore "github.com/libp2p/go-libp2p/core/peerstore"
ma "github.com/multiformats/go-multiaddr"
"github.com/syndtr/goleveldb/leveldb"
"github.com/tkanos/gonfig"
)
func main() {
configuration := files.Configuration{}
err := gonfig.GetConf(files.GetFileName(), &configuration)
if err != nil {
fmt.Println(err)
os.Exit(500)
}
dbPath := configuration.DBPath
dbPath_cache := configuration.DBCachePath
dbPath_accounts := configuration.DBAccountsPath
// // Abrir la base de datos (creará una si no existe)
db, err := leveldb.OpenFile(dbPath, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
dbCache, err := leveldb.OpenFile(dbPath_cache, nil)
if err != nil {
log.Fatal(err)
}
defer dbCache.Close()
dbAccounts, err := leveldb.OpenFile(dbPath_accounts, nil)
if err != nil {
log.Fatal(err)
}
defer dbAccounts.Close()
//Parse options from the command line
listenF := flag.Int("l", 0, "wait for incoming connections")
target := flag.String("d", "", "target peer to dial")
secio := flag.Bool("secio", false, "enable secio")
seed := flag.Int64("seed", 0, "set random seed for id generation")
flag.Parse()
if *listenF == 0 {
log.Fatal("Please provide a port to bind on with -l")
}
ha, err := files.MakeBasicHost(*listenF, *secio, *seed)
if err != nil {
log.Fatal(err)
}
if *target == "" {
log.Println("listening for connections")
// Set a stream handler on host A. /p2p/1.0.0 is
// a user-defined protocol name.
ha.SetStreamHandler("/p2p/1.0.0", func(s net.Stream) {
go HandleStream(s, db, dbAccounts, dbCache)
})
select {} // hang forever
/**** This is where the listener code ends ****/
} else {
ipfsaddr, err := ma.NewMultiaddr(*target)
if err != nil {
log.Fatalln(err)
}
pid, err := ipfsaddr.ValueForProtocol(ma.P_IPFS)
if err != nil {
log.Fatalln(err)
}
peerid, err := peer.Decode(pid)
if err != nil {
log.Fatalln(err)
}
// Decapsulate the /ipfs/<peerID> part from the target
// /ip4/<a.b.c.d>/ipfs/<peer> becomes /ip4/<a.b.c.d>
targetPeerAddr, _ := ma.NewMultiaddr(
fmt.Sprintf("/ipfs/%s", peerid.String()))
targetAddr := ipfsaddr.Decapsulate(targetPeerAddr)
// We have a peer ID and a targetAddr so we add it to the peerstore
// so LibP2P knows how to contact it
ha.Peerstore().AddAddr(peerid, targetAddr, pstore.PermanentAddrTTL)
log.Println("opening stream")
// make a new stream from host B to host A
// it should be handled on host A by the handler we set above because
// we use the same /p2p/1.0.0 protocol
s, err := ha.NewStream(context.Background(), peerid, "/p2p/1.0.0")
if err != nil {
log.Fatalln(err)
}
// Create a buffered stream so that read and writes are non blocking.
rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s))
// Create a thread to read and write data.
stopChan := make(chan struct{})
go files.WriteData(rw, db, dbAccounts, dbCache, stopChan)
go files.ReadData(rw, db, dbAccounts, dbCache, stopChan)
select {} // hang forever
}
}
func HandleStream(s net.Stream, db *leveldb.DB, dbAccounts *leveldb.DB, dbCache *leveldb.DB) {
log.Println("Got a new stream!")
configuration := files.Configuration{}
err := gonfig.GetConf(files.GetFileName(), &configuration)
if err != nil {
fmt.Println(err)
}
transactions := []files.Transaction{
{
Sender: configuration.RootSender,
Recipient: configuration.RootRecipient,
Amount: configuration.RootAmount,
Nonce: configuration.RootNonce,
},
}
iter_check := db.NewIterator(nil, nil)
defer iter_check.Release()
empty := !iter_check.Next()
stopChan := make(chan struct{})
rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s))
if empty {
//Se crea el bloque raíz con índice 1, previous hash "" y una transacción con información contenida en el config file
block := files.GenerateBlock(1, "", transactions)
if err := files.UpdateBlockChain(db, dbCache, block); err != nil {
log.Fatal(err)
}
// Create a buffer stream for non blocking read and write.
jsonPersona := files.GetBlock(db)
bytes, err := json.Marshal(jsonPersona)
if err != nil {
log.Println(err)
}
rw.WriteString(fmt.Sprintf("%s\n", string(bytes)))
rw.Flush()
}
go files.ReadData(rw, db, dbAccounts, dbCache, stopChan)
go files.WriteData(rw, db, dbAccounts, dbCache, stopChan)
// stream 's' will stay open until you close it (or the other side closes it).
}