forked from denkhaus/go-bitshares
/
generator.go
328 lines (274 loc) · 7.24 KB
/
generator.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
322
323
324
325
326
327
328
package main
import (
"bytes"
"encoding/json"
"fmt"
"go/format"
"html/template"
"io/ioutil"
"os"
"strconv"
"strings"
"github.com/denkhaus/gojson"
"github.com/iuouiyiuty/bitshares/api"
"github.com/iuouiyiuty/bitshares/gen/data"
"github.com/iuouiyiuty/bitshares/tests"
"github.com/iuouiyiuty/bitshares/types"
"github.com/iuouiyiuty/bitshares/util"
"github.com/juju/errors"
"github.com/pquerna/ffjson/ffjson"
"github.com/stretchr/objx"
"gopkg.in/tomb.v2"
// importing this initializes sample data fetching
_ "github.com/iuouiyiuty/bitshares/gen/samples"
)
type Unmarshalable interface {
UnmarshalJSON(input []byte) error
}
var (
sampleDataTemplate *template.Template
samplesDir = "samples"
operationsDir = "operations"
genChan = make(chan GenData, 40)
tb = tomb.Tomb{}
// do not change order here
knownTypes = []Unmarshalable{
//&types.AccountOptions{},
// &types.Asset{},
&types.AssetAmount{},
&types.AssetFeed{},
// &types.AssetOptions{},
&types.GrapheneID{},
//&types.BitAssetDataOptions{},
&types.Authority{},
//&types.Memo{},
&types.Price{},
&types.PriceFeed{},
//&types.Votes{},
&types.Time{},
//&types.PublicKey{},
//&types.Account{},
}
)
type GenData struct {
Type types.OperationType
Data objx.Map
}
func main() {
defer close(genChan)
api := api.New(tests.WsFullApiUrl, tests.RpcFullApiUrl)
if err := api.Connect(); err != nil {
handleError(errors.Annotate(err, "Connect"))
}
api.OnError(func(err error) {
handleError(errors.Annotate(err, "OnError"))
})
//init templates
tmpl, err := template.ParseFiles("templates/opsampledata.go.tmpl")
if err != nil {
handleError(errors.Annotate(err, "ParseFiles"))
}
sampleDataTemplate = tmpl
// start generate goroutine
tb.Go(func() error {
return generate(genChan)
})
dataStore := NewOpDataStore()
if err := dataStore.Init(data.OpSampleMap, genChan); err != nil {
handleError(errors.Annotate(err, "init datastore"))
}
//TODO: save last scanned block and reapply
block := uint64(20435987)
fmt.Println("loop blocks")
for tb.Alive() {
resp, err := api.CallWsAPI(0, "get_block", block)
if err != nil {
handleError(errors.Annotate(err, "GetBlock"))
}
m := objx.New(resp)
trxs := m.Get("transactions")
// enumerate Transactions
trxs.EachInter(func(_ int, trx interface{}) bool {
ops := objx.New(trx).Get("operations")
// enumerate Operations
ops.EachInter(func(_ int, o interface{}) bool {
op := o.([]interface{})
opType := types.OperationType(types.Int8(op[0].(float64)))
opData := objx.New(op[1])
blob := NewOperationBlob(opData)
ok, err := dataStore.Evaluate(opType, blob, block)
if err != nil {
handleError(errors.Annotate(err, "Evaluate"))
}
if ok && tb.Alive() {
genChan <- GenData{
Type: opType,
Data: opData,
}
}
return true
})
return true
})
block++
}
if err := tb.Err(); err != nil {
handleError(errors.Annotate(err, "main"))
}
}
func generate(ch chan GenData) error {
for {
select {
case data := <-ch:
if err := generateSampleData(data); err != nil {
return errors.Annotate(err, "generateSampleData")
}
if err := generateOpData(data); err != nil {
return errors.Annotate(err, "generateOpData")
}
case <-tb.Dying():
return nil
default:
}
}
}
func generateOpData(d GenData) error {
s, err := data.GetSampleByType(d.Type)
if err != nil {
return errors.Annotate(err, "GetSampleByType")
}
sample, err := strconv.Unquote(s)
if err != nil {
return errors.Annotate(err, "Unquote")
}
//fmt.Printf("generate struct by sample %+v\n", sample)
buf, err := gojson.GenerateWithTypeGuessing(
strings.NewReader(sample),
gojson.ParseJson, d.Type.OperationName(),
"operations", []string{"json"}, true, true,
guessStructType,
)
if err != nil {
return errors.Annotate(err, "GenerateWithTypeGuessing")
}
fmt.Println("generated struct ", string(buf))
return nil
}
func generateSampleData(d GenData) error {
opName := d.Type.OperationName()
sampleDataJSON, err := json.MarshalIndent(d.Data, "", " ")
if err != nil {
return errors.Annotate(err, "MarshalIndent")
}
sampleData := fmt.Sprintf("`%s`", sampleDataJSON)
//update sample map too
data.OpSampleMap[d.Type] = sampleData
buf := bytes.NewBuffer(nil)
err = sampleDataTemplate.Execute(buf, struct {
SampleDataOpType string
SampleData interface{}
SampleDataVarName string
}{
SampleDataOpType: d.Type.String(),
SampleData: template.HTML(sampleData),
SampleDataVarName: fmt.Sprintf("sampleData%s", opName),
})
if err != nil {
return errors.Annotate(err, "Execute")
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
return errors.Annotate(err, "Source")
}
fileName := strings.ToLower(fmt.Sprintf("%s/%s.go", samplesDir, opName))
if err := ioutil.WriteFile(fileName, formatted, 0622); err != nil {
return errors.Annotate(err, "WriteFile")
}
return nil
}
func handleError(err error) {
fmt.Println("error: ", errors.ErrorStack(err))
if tb.Alive() {
//kill generator goroutine and wait
tb.Kill(err)
tb.Wait()
}
os.Exit(1)
}
func guessStructType(value interface{}, suggestedType string) (string, error) {
//util.Dump("valueToGuess", value)
// util.DumpJSON("suggestedType", suggestedType)
for _, t := range knownTypes {
v, err := ffjson.Marshal(value)
if err != nil {
return "", errors.Annotate(err, "Marshal")
}
//make local copy of known type
typ := t
// util.Dump("data", v)
if err := typ.UnmarshalJSON(v); err == nil {
// util.Dump("compare-1", typ)
// util.Dump("compare-2", value)
switch o := typ.(type) {
case *types.GrapheneID:
if value.(string) == o.String() {
return "types.GrapheneID", nil
}
case *types.Time:
if value.(string) == o.String() {
return "types.Time", nil
}
// case *types.PublicKey:
// if value.(string) == o.String() {
// return "types.PublicKey", nil
// }
case *types.AccountOptions:
if bytes.Equal(v, util.ToBytes(typ)) {
return "types.AccountOptions", nil
}
case *types.AssetAmount:
if bytes.Equal(v, util.ToBytes(typ)) {
return "types.AssetAmount", nil
}
case *types.Authority:
if bytes.Equal(v, util.ToBytes(typ)) {
return "types.Authority", nil
}
case *types.Memo:
if bytes.Equal(v, util.ToBytes(typ)) {
return "types.Memo", nil
}
// case *types.Votes:
// if bytes.Equal(v, util.ToBytes(typ)) {
// return "types.Votes", nil
// }
case *types.Price:
if bytes.Equal(v, util.ToBytes(typ)) {
return "types.Price", nil
}
case *types.PriceFeed:
if bytes.Equal(v, util.ToBytes(typ)) {
return "types.PriceFeed", nil
}
case *types.AssetFeed:
if bytes.Equal(v, util.ToBytes(typ)) {
return "types.AssetFeed", nil
}
}
// if val1, ok := value.(map[string]interface{}); ok {
// val2 := util.ToMap(typ)
// util.Dump("compare-1", val1)
// util.Dump("compare-2", val2)
// if reflect.DeepEqual(val1, val2) {
// util.Dump("solved", typ)
// return "lala", nil
// }
// }
// name := reflect.ValueOf(typ).Type().Name()
// util.Dump("solved", typ)
// util.Dump("typeName", name)
//o1 := util.ToMap(value)
}
}
return suggestedType, nil
}