forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.go
118 lines (95 loc) · 2.45 KB
/
import.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
package main
import (
"bufio"
"context"
"flag"
"fmt"
"os"
"time"
"github.com/gnolang/gno/tm2/pkg/amino"
"github.com/gnolang/gno/tm2/pkg/bft/rpc/client"
"github.com/gnolang/gno/tm2/pkg/commands"
"github.com/gnolang/gno/tm2/pkg/errors"
"github.com/gnolang/gno/tm2/pkg/std"
_ "github.com/gnolang/gno/tm2/pkg/sdk/auth" // XXX better way?
_ "github.com/gnolang/gno/tm2/pkg/sdk/bank"
_ "github.com/gnolang/gno/tm2/pkg/sdk/vm"
)
type importCfg struct {
rootCfg *config
inFile string
}
func newImportCommand(rootCfg *config) *commands.Command {
cfg := &importCfg{
rootCfg: rootCfg,
}
return commands.NewCommand(
commands.Metadata{
Name: "import",
ShortUsage: "import [flags] <file>",
ShortHelp: "Import transactions from file",
},
cfg,
func(ctx context.Context, _ []string) error {
return execImport(ctx, cfg)
},
)
}
func (c *importCfg) RegisterFlags(fs *flag.FlagSet) {
fs.StringVar(&c.inFile, "in", defaultFilePath, "input file path")
}
func execImport(ctx context.Context, c *importCfg) error {
// Initial validation
if len(c.inFile) == 0 {
return errors.New("input file path not specified")
}
// Read the input file
file, err := os.Open(c.inFile)
if err != nil {
return fmt.Errorf("unable to open input file, %w", err)
}
defer file.Close()
// Start the WS connection to the node
node := client.NewHTTP(c.rootCfg.remote, "/websocket")
index := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
select {
case <-ctx.Done():
// Stop signal received while parsing
// the import file
return nil
default:
print(".")
line := scanner.Text()
if len(line) == 0 {
return fmt.Errorf("empty line encountered at %d", index)
}
var tx std.Tx
amino.MustUnmarshalJSON([]byte(line), &tx)
txbz := amino.MustMarshal(tx)
res, err := node.BroadcastTxSync(txbz)
if err != nil || res.Error != nil {
print("!")
// wait for next block and try again.
// TODO: actually wait 1 block instead of fudging it.
time.Sleep(20 * time.Second)
res, err := node.BroadcastTxSync(txbz)
if err != nil || res.Error != nil {
if err != nil {
fmt.Println("SECOND ERROR", err)
} else {
fmt.Println("SECOND ERROR!", res.Error)
}
fmt.Println(line)
return errors.Wrap(err, "broadcasting tx %d", index)
}
}
index++
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("error encountered while reading file, %w", err)
}
return nil
}