-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
217 lines (182 loc) · 4.67 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
// Command txvmbcd is a minimal TxVM blockchain server.
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"strconv"
"sync"
"time"
"github.com/chain/txvm/errors"
"github.com/chain/txvm/protocol"
"github.com/chain/txvm/protocol/bc"
"github.com/golang/protobuf/proto"
_ "github.com/mattn/go-sqlite3"
)
var (
bbmu sync.Mutex
bb *protocol.BlockBuilder
)
var blockInterval = 5 * time.Second
var (
initialBlock *bc.Block
chain *protocol.Chain
)
func main() {
ctx := context.Background()
var (
addr = flag.String("addr", "localhost:2423", "server listen address")
dbfile = flag.String("db", "", "path to block storage db")
)
flag.Parse()
db, err := sql.Open("sqlite3", *dbfile)
if err != nil {
log.Fatal(err)
}
defer db.Close()
heights := make(chan uint64)
bs, err := newBlockStore(db, heights)
if err != nil {
log.Fatal(err)
}
initialBlock, err = bs.GetBlock(ctx, 1)
if err != nil {
log.Fatal(err)
}
chain, err = protocol.NewChain(ctx, initialBlock, bs, heights)
if err != nil {
log.Fatal("initializing Chain: ", err)
}
_, err = chain.Recover(ctx)
if err != nil {
log.Fatal(err)
}
initialBlockID := initialBlock.Hash()
listener, err := net.Listen("tcp", *addr)
if err != nil {
log.Fatal(err)
}
log.Printf("listening on %s, initial block ID %x", listener.Addr(), initialBlockID.Bytes())
http.HandleFunc("/submit", submit)
http.HandleFunc("/get", get)
http.Serve(listener, nil)
}
func submit(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
bits, err := ioutil.ReadAll(req.Body)
if err != nil {
httpErrf(w, http.StatusInternalServerError, "reading request body: %s", err)
return
}
var rawTx bc.RawTx
err = proto.Unmarshal(bits, &rawTx)
if err != nil {
httpErrf(w, http.StatusBadRequest, "parsing request body: %s", err)
return
}
tx, err := bc.NewTx(rawTx.Program, rawTx.Version, rawTx.Runlimit)
if err != nil {
httpErrf(w, http.StatusBadRequest, "building tx: %s", err)
return
}
bbmu.Lock()
defer bbmu.Unlock()
if bb == nil {
bb = protocol.NewBlockBuilder()
nextBlockTime := time.Now().Add(blockInterval)
st := chain.State()
if st.Header == nil {
err = st.ApplyBlockHeader(initialBlock.BlockHeader)
if err != nil {
httpErrf(w, http.StatusInternalServerError, "initializing empty state: %s", err)
return
}
}
err := bb.Start(chain.State(), bc.Millis(nextBlockTime))
if err != nil {
httpErrf(w, http.StatusInternalServerError, "starting a new tx pool: %s", err)
return
}
log.Printf("starting new block, will commit at %s", nextBlockTime)
time.AfterFunc(blockInterval, func() {
bbmu.Lock()
defer bbmu.Unlock()
defer func() { bb = nil }()
unsignedBlock, newSnapshot, err := bb.Build()
if err != nil {
log.Fatal(errors.Wrap(err, "building new block"))
}
if len(unsignedBlock.Transactions) == 0 {
log.Print("skipping commit of empty block")
return
}
err = chain.CommitAppliedBlock(ctx, &bc.Block{UnsignedBlock: unsignedBlock}, newSnapshot)
if err != nil {
log.Fatal(errors.Wrap(err, "committing new block"))
}
log.Printf("committed block %d with %d transaction(s)", unsignedBlock.Height, len(unsignedBlock.Transactions))
})
}
err = bb.AddTx(bc.NewCommitmentsTx(tx))
if err != nil {
httpErrf(w, http.StatusBadRequest, "adding tx to pool: %s", err)
return
}
log.Printf("added tx %x to the pending block", tx.ID.Bytes())
w.WriteHeader(http.StatusNoContent)
}
func get(w http.ResponseWriter, req *http.Request) {
wantStr := req.FormValue("height")
var (
want uint64 = 1
err error
)
if wantStr != "" {
want, err = strconv.ParseUint(wantStr, 10, 64)
if err != nil {
httpErrf(w, http.StatusBadRequest, "parsing height: %s", err)
return
}
}
height := chain.Height()
if want == 0 {
want = height
}
if want > height {
ctx := req.Context()
waiter := chain.BlockWaiter(want)
select {
case <-waiter:
// ok
case <-ctx.Done():
httpErrf(w, http.StatusRequestTimeout, "timed out")
return
}
}
ctx := req.Context()
b, err := chain.GetBlock(ctx, want)
if err != nil {
httpErrf(w, http.StatusInternalServerError, "getting block %d: %s", want, err)
return
}
bits, err := b.Bytes()
if err != nil {
httpErrf(w, http.StatusInternalServerError, "serializing block %d: %s", want, err)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
_, err = w.Write(bits)
if err != nil {
httpErrf(w, http.StatusInternalServerError, "sending response: %s", err)
return
}
}
func httpErrf(w http.ResponseWriter, code int, msgfmt string, args ...interface{}) {
http.Error(w, fmt.Sprintf(msgfmt, args...), code)
log.Printf(msgfmt, args...)
}