-
Notifications
You must be signed in to change notification settings - Fork 531
/
chain.go
355 lines (297 loc) · 8.56 KB
/
chain.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package chaincmdrunner
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/pkg/errors"
"github.com/tendermint/starport/starport/pkg/chaincmd"
"github.com/tendermint/starport/starport/pkg/cmdrunner/step"
"github.com/tendermint/starport/starport/pkg/cosmosver"
)
// Start starts the blockchain.
func (r Runner) Start(ctx context.Context, args ...string) error {
return r.run(
ctx,
runOptions{wrappedStdErrMaxLen: 50000},
r.chainCmd.StartCommand(args...),
)
}
// LaunchpadStartRestServer start launchpad rest server.
func (r Runner) LaunchpadStartRestServer(ctx context.Context, apiAddress, rpcAddress string) error {
return r.run(
ctx,
runOptions{wrappedStdErrMaxLen: 50000},
r.chainCmd.LaunchpadRestServerCommand(apiAddress, rpcAddress),
)
}
// Init inits the blockchain.
func (r Runner) Init(ctx context.Context, moniker string) error {
return r.run(ctx, runOptions{}, r.chainCmd.InitCommand(moniker))
}
// KV holds a key, value pair.
type KV struct {
key string
value string
}
// NewKV returns a new key, value pair.
func NewKV(key, value string) KV {
return KV{key, value}
}
// LaunchpadSetConfigs updates configurations for a launchpad app.
func (r Runner) LaunchpadSetConfigs(ctx context.Context, kvs ...KV) error {
for _, kv := range kvs {
if err := r.run(
ctx,
runOptions{},
r.chainCmd.LaunchpadSetConfigCommand(kv.key, kv.value),
); err != nil {
return err
}
}
return nil
}
var gentxRe = regexp.MustCompile(`(?m)"(.+?)"`)
// Gentx generates a genesis tx carrying a self delegation.
func (r Runner) Gentx(
ctx context.Context,
validatorName,
selfDelegation string,
options ...chaincmd.GentxOption,
) (gentxPath string, err error) {
b := &bytes.Buffer{}
if err := r.run(ctx, runOptions{
stdout: b,
stderr: b,
stdin: os.Stdin,
}, r.chainCmd.GentxCommand(validatorName, selfDelegation, options...)); err != nil {
return "", err
}
return gentxRe.FindStringSubmatch(b.String())[1], nil
}
// CollectGentxs collects gentxs.
func (r Runner) CollectGentxs(ctx context.Context) error {
return r.run(ctx, runOptions{}, r.chainCmd.CollectGentxsCommand())
}
// ValidateGenesis validates genesis.
func (r Runner) ValidateGenesis(ctx context.Context) error {
return r.run(ctx, runOptions{}, r.chainCmd.ValidateGenesisCommand())
}
// UnsafeReset resets the blockchain database.
func (r Runner) UnsafeReset(ctx context.Context) error {
return r.run(ctx, runOptions{}, r.chainCmd.UnsafeResetCommand())
}
// ShowNodeID shows node id.
func (r Runner) ShowNodeID(ctx context.Context) (nodeID string, err error) {
b := &bytes.Buffer{}
err = r.run(ctx, runOptions{stdout: b}, r.chainCmd.ShowNodeIDCommand())
nodeID = strings.TrimSpace(b.String())
return
}
// NodeStatus keeps info about node's status.
type NodeStatus struct {
ChainID string
}
// Status returns the node's status.
func (r Runner) Status(ctx context.Context) (NodeStatus, error) {
b := newBuffer()
if err := r.run(ctx, runOptions{stdout: b, stderr: b}, r.chainCmd.StatusCommand()); err != nil {
return NodeStatus{}, err
}
var chainID string
data, err := b.JSONEnsuredBytes()
if err != nil {
return NodeStatus{}, err
}
version := r.chainCmd.SDKVersion()
switch {
case version.GTE(cosmosver.StargateFortyVersion):
out := struct {
NodeInfo struct {
Network string `json:"network"`
} `json:"NodeInfo"`
}{}
if err := json.Unmarshal(data, &out); err != nil {
return NodeStatus{}, err
}
chainID = out.NodeInfo.Network
default:
out := struct {
NodeInfo struct {
Network string `json:"network"`
} `json:"node_info"`
}{}
if err := json.Unmarshal(data, &out); err != nil {
return NodeStatus{}, err
}
chainID = out.NodeInfo.Network
}
return NodeStatus{
ChainID: chainID,
}, nil
}
// BankSend sends amount from fromAccount to toAccount.
func (r Runner) BankSend(ctx context.Context, fromAccount, toAccount, amount string) (string, error) {
b := newBuffer()
opt := []step.Option{
r.chainCmd.BankSendCommand(fromAccount, toAccount, amount),
}
if r.chainCmd.KeyringPassword() != "" {
input := &bytes.Buffer{}
fmt.Fprintln(input, r.chainCmd.KeyringPassword())
fmt.Fprintln(input, r.chainCmd.KeyringPassword())
fmt.Fprintln(input, r.chainCmd.KeyringPassword())
opt = append(opt, step.Write(input.Bytes()))
}
if err := r.run(ctx, runOptions{stdout: b}, opt...); err != nil {
if strings.Contains(err.Error(), "key not found") || // stargate
strings.Contains(err.Error(), "unknown address") || // launchpad
strings.Contains(b.String(), "item could not be found") { // launchpad
return "", errors.New("account doesn't have any balances")
}
return "", err
}
txResult, err := decodeTxResult(b)
if err != nil {
return "", err
}
if txResult.Code > 0 {
return "", fmt.Errorf("cannot send tokens (SDK code %d): %s", txResult.Code, txResult.RawLog)
}
return txResult.TxHash, nil
}
// WaitTx waits until a tx is successfully added to a block and can be queried
func (r Runner) WaitTx(ctx context.Context, txHash string, retryDelay time.Duration, maxRetry int) error {
retry := 0
// retry querying the request
checkTx := func() error {
b := newBuffer()
if err := r.run(ctx, runOptions{stdout: b}, r.chainCmd.QueryTxCommand(txHash)); err != nil {
// filter not found error and check for max retry
if !strings.Contains(err.Error(), "not found") {
return backoff.Permanent(err)
}
retry++
if retry == maxRetry {
return backoff.Permanent(fmt.Errorf("can't retrieve tx %s", txHash))
}
return err
}
// parse tx and check code
txResult, err := decodeTxResult(b)
if err != nil {
return backoff.Permanent(err)
}
if txResult.Code != 0 {
return backoff.Permanent(fmt.Errorf("tx %s failed: %s", txHash, txResult.RawLog))
}
return nil
}
return backoff.Retry(checkTx, backoff.WithContext(backoff.NewConstantBackOff(retryDelay), ctx))
}
// Export exports the state of the chain into the specified file
func (r Runner) Export(ctx context.Context, exportedFile string) error {
stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
if err := r.run(ctx, runOptions{stdout: stdout, stderr: stderr}, r.chainCmd.ExportCommand()); err != nil {
return err
}
// Exported genesis is written on stderr from Cosmos-SDK v0.44.0
var exportedState []byte
if stdout.Len() > 0 {
exportedState = stdout.Bytes()
} else {
exportedState = stderr.Bytes()
}
// Save the new state
return os.WriteFile(exportedFile, exportedState, 0644)
}
// EventSelector is used to query events.
type EventSelector struct {
typ string
attr string
value string
}
// NewEventSelector creates a new event selector.
func NewEventSelector(typ, addr, value string) EventSelector {
return EventSelector{typ, addr, value}
}
// Event represents a TX event.
type Event struct {
Type string
Attributes []EventAttribute
Time time.Time
}
// EventAttribute holds event's attributes.
type EventAttribute struct {
Key string
Value string
}
// QueryTxEvents queries tx events by event selectors.
func (r Runner) QueryTxEvents(
ctx context.Context,
selector EventSelector,
moreSelectors ...EventSelector,
) ([]Event, error) {
// prepare the slector.
var list []string
eventsSelectors := append([]EventSelector{selector}, moreSelectors...)
for _, event := range eventsSelectors {
list = append(list, fmt.Sprintf("%s.%s=%s", event.typ, event.attr, event.value))
}
query := strings.Join(list, "&")
// execute the commnd and parse the output.
b := newBuffer()
if err := r.run(ctx, runOptions{stdout: b}, r.chainCmd.QueryTxEventsCommand(query)); err != nil {
return nil, err
}
out := struct {
Txs []struct {
Logs []struct {
Events []struct {
Type string `json:"type"`
Attrs []struct {
Key string `json:"key"`
Value string `json:"value"`
} `json:"attributes"`
} `json:"events"`
} `json:"logs"`
TimeStamp string `json:"timestamp"`
} `json:"txs"`
}{}
data, err := b.JSONEnsuredBytes()
if err != nil {
return nil, err
}
if err := json.Unmarshal(data, &out); err != nil {
return nil, err
}
var events []Event
for _, tx := range out.Txs {
for _, log := range tx.Logs {
for _, e := range log.Events {
var attrs []EventAttribute
for _, attr := range e.Attrs {
attrs = append(attrs, EventAttribute{
Key: attr.Key,
Value: attr.Value,
})
}
txTime, err := time.Parse(time.RFC3339, tx.TimeStamp)
if err != nil {
return nil, err
}
events = append(events, Event{
Type: e.Type,
Attributes: attrs,
Time: txTime,
})
}
}
}
return events, nil
}