-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
377 lines (327 loc) · 10.8 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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package main
import (
"context"
"fmt"
_ "net/http/pprof"
"os"
"os/signal"
"path"
"runtime"
"strings"
"sync"
"github.com/threefoldtech/rivine/modules/transactionpool"
"github.com/ethereum/go-ethereum/log"
"github.com/threefoldfoundation/tfchain/pkg/cli"
"github.com/threefoldfoundation/tfchain/pkg/config"
"github.com/threefoldfoundation/tfchain/pkg/eth/erc20"
"github.com/threefoldfoundation/tfchain/pkg/persist"
"github.com/spf13/cobra"
tfchaintypes "github.com/threefoldfoundation/tfchain/pkg/types"
"github.com/threefoldtech/rivine/modules"
"github.com/threefoldtech/rivine/modules/consensus"
"github.com/threefoldtech/rivine/modules/gateway"
rivinetypes "github.com/threefoldtech/rivine/types"
)
// Commands defines the CLI Commands for the Bridge as well as its in-memory state.
type Commands struct {
RPCaddr string
BlockchainInfo rivinetypes.BlockchainInfo
ChainConstants rivinetypes.ChainConstants
BootstrapPeers []modules.NetAddress
EthNetworkName string
// eth port for light client
EthPort uint16
// eth account flags
accJSON string
accPass string
EthLog int
ContractAddress string
RootPersistentDir string
transactionDB *persist.TransactionDB
}
// Root represents the root (`bridged`) command,
// starting a bridged daemon instance, running until the user intervenes.
func (cmd *Commands) Root(_ *cobra.Command, args []string) (cmdErr error) {
log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(cmd.EthLog), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
log.Info("starting bridge", "version", cmd.BlockchainInfo.ChainVersion.String())
log.Info("loading network config, registering types and loading rivine transaction db (0/4)...")
switch cmd.BlockchainInfo.NetworkName {
case config.NetworkNameStandard:
cmd.transactionDB, cmdErr = persist.NewTransactionDB(cmd.rootPerDir(), config.GetStandardnetGenesisMintCondition())
if cmdErr != nil {
return fmt.Errorf("failed to create tfchain transaction DB for tfchain standard: %v", cmdErr)
}
cmd.ChainConstants = config.GetStandardnetGenesis()
// Register the transaction controllers for all transaction versions
// supported on the standard network
tfchaintypes.RegisterTransactionTypesForStandardNetwork(cmd.transactionDB, &tfchaintypes.NopERC20TransactionValidator{},
cmd.ChainConstants.CurrencyUnits.OneCoin, config.GetStandardDaemonNetworkConfig())
// Forbid the usage of MultiSignatureCondition (and thus the multisig feature),
// until the blockchain reached a height of 42000 blocks.
tfchaintypes.RegisterBlockHeightLimitedMultiSignatureCondition(42000)
if len(cmd.BootstrapPeers) == 0 {
cmd.BootstrapPeers = config.GetStandardnetBootstrapPeers()
}
if cmd.EthNetworkName == "" {
// default to main network on standard net
cmd.EthNetworkName = "main"
}
case config.NetworkNameTest:
cmd.transactionDB, cmdErr = persist.NewTransactionDB(cmd.rootPerDir(), config.GetTestnetGenesisMintCondition())
if cmdErr != nil {
return fmt.Errorf("failed to create tfchain transaction DB for tfchain testnet: %v", cmdErr)
}
// get chain constants and bootstrap peers
cmd.ChainConstants = config.GetTestnetGenesis()
// Register the transaction controllers for all transaction versions
// supported on the test network
tfchaintypes.RegisterTransactionTypesForTestNetwork(cmd.transactionDB, &tfchaintypes.NopERC20TransactionValidator{},
cmd.ChainConstants.CurrencyUnits.OneCoin, config.GetTestnetDaemonNetworkConfig())
// Use our custom MultiSignatureCondition, just for testing purposes
tfchaintypes.RegisterBlockHeightLimitedMultiSignatureCondition(0)
if len(cmd.BootstrapPeers) == 0 {
cmd.BootstrapPeers = config.GetTestnetBootstrapPeers()
}
if cmd.EthNetworkName == "" {
// default to ropsten network on testnet
cmd.EthNetworkName = "ropsten"
}
case config.NetworkNameDev:
cmd.transactionDB, cmdErr = persist.NewTransactionDB(cmd.rootPerDir(), config.GetDevnetGenesisMintCondition())
if cmdErr != nil {
return fmt.Errorf("failed to create tfchain transaction DB for tfchain devnet: %v", cmdErr)
}
// get chain constants and bootstrap peers
cmd.ChainConstants = config.GetDevnetGenesis()
// Register the transaction controllers for all transaction versions
// supported on the dev network
tfchaintypes.RegisterTransactionTypesForDevNetwork(cmd.transactionDB, &tfchaintypes.NopERC20TransactionValidator{},
cmd.ChainConstants.CurrencyUnits.OneCoin, config.GetDevnetDaemonNetworkConfig())
// Use our custom MultiSignatureCondition, just for testing purposes
tfchaintypes.RegisterBlockHeightLimitedMultiSignatureCondition(0)
if len(cmd.BootstrapPeers) == 0 {
cmd.BootstrapPeers = config.GetDevnetBootstrapPeers()
}
if cmd.EthNetworkName == "" {
// default to rinkeby network on devnet
cmd.EthNetworkName = "rinkeby"
}
default:
return fmt.Errorf(
"%q is an invalid network name, has to be one of {standard,testnet,devnet}",
cmd.BlockchainInfo.Name)
}
ctx, cancel := context.WithCancel(context.Background())
// load all modules
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
log.Info("loading rivine gateway module (1/4)...")
gateway, err := gateway.New(
cmd.RPCaddr, true, cmd.perDir("gateway"),
cmd.BlockchainInfo, cmd.ChainConstants, cmd.BootstrapPeers)
if err != nil {
log.Error("Failed to create gateway module", "err", err)
cancel()
cmdErr = err
return
}
defer func() {
log.Info("Closing gateway module...")
err := gateway.Close()
if err != nil {
log.Error("Failed to close gateway module", "err", err)
}
}()
log.Info("loading rivine consensus module (2/4)...")
cs, err := consensus.New(
gateway, true, cmd.perDir("consensus"),
cmd.BlockchainInfo, cmd.ChainConstants)
if err != nil {
log.Error("Failed to create consensus module", "err", err)
cancel()
cmdErr = err
return
}
defer func() {
log.Info("Closing consensus module...")
err := cs.Close()
if err != nil {
log.Error("Failed to close consensus module", "err", err)
}
}()
err = cmd.transactionDB.SubscribeToConsensusSet(cs)
if err != nil {
log.Error("Failed to subscribe transactionDB module to consensus module", "err", err)
cancel()
cmdErr = err
return
}
log.Info("loading transactionpool module (3/4)...")
tpool, err := transactionpool.New(cs, gateway, cmd.perDir("transactionpool"), cmd.BlockchainInfo, cmd.ChainConstants)
if err != nil {
log.Error("Failed to create txpool module", "err", err)
cancel()
cmdErr = err
return
}
defer func() {
log.Info("Closing transactionpool module...")
err := tpool.Close()
if err != nil {
log.Error("Failed to close the transactionpool module", "err", err)
}
}()
log.Info("loading bridged module (4/4)...")
bridged, err := erc20.NewBridge(
cs, cmd.transactionDB, tpool, cmd.EthPort, cmd.accJSON, cmd.accPass, cmd.EthNetworkName, cmd.ContractAddress, cmd.perDir("bridge"),
cmd.BlockchainInfo, cmd.ChainConstants, ctx.Done())
if err != nil {
log.Error("Failed to create bridge module", "err", err)
cancel()
cmdErr = err
return
}
defer func() {
log.Info("closing bridged module...")
err := bridged.Close()
if err != nil {
log.Error("Failed to close bridge module", "err", err)
}
}()
log.Info("bridged is up and running...")
// wait until done
<-ctx.Done()
}()
// stop the server if a kill signal is caught
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, os.Kill)
// wait for server to be killed or the process to be done
select {
case <-sigChan:
log.Info("Caught stop signal, quitting...")
case <-ctx.Done():
log.Info("context is done, quitting...")
}
cancel()
wg.Wait()
log.Info("Goodbye!")
return
}
func (cmd *Commands) rootPerDir() string {
return path.Join(
cmd.RootPersistentDir,
cmd.BlockchainInfo.Name, cmd.BlockchainInfo.NetworkName)
}
func (cmd *Commands) perDir(module string) string {
return path.Join(cmd.rootPerDir(), module)
}
// Version represents the version (`bridged version`) command,
// returning the version of the tool, dependencies and Go,
// as well as the OS and Arch type.
func (cmd *Commands) Version(_ *cobra.Command, _ []string) {
var postfix string
switch cmd.BlockchainInfo.NetworkName {
case "devnet":
postfix = "-dev"
case "testnet":
postfix = "-testing"
case "standard": // ""
default:
postfix = "-???"
}
fmt.Printf("%s Bridge Daemon v%s%s\n",
strings.Title(cmd.BlockchainInfo.Name),
cmd.BlockchainInfo.ChainVersion.String(), postfix)
fmt.Println("Rivine Protocol v" + cmd.BlockchainInfo.ProtocolVersion.String())
fmt.Println()
fmt.Printf("Go Version v%s\r\n", runtime.Version()[2:])
fmt.Printf("GOOS %s\r\n", runtime.GOOS)
fmt.Printf("GOARCH %s\r\n", runtime.GOARCH)
}
func main() {
cmd := new(Commands)
cmd.RPCaddr = ":23118"
cmd.BlockchainInfo = config.GetBlockchainInfo()
// define commands
cmdRoot := &cobra.Command{
Use: "bridged",
Short: "start the bridged daemon",
Long: `start the bridged daemon`,
Args: cobra.ExactArgs(0),
SilenceUsage: true,
RunE: cmd.Root,
}
cmdVersion := &cobra.Command{
Use: "version",
Short: "show versions of this tool",
Args: cobra.ExactArgs(0),
Run: cmd.Version,
}
// define command tree
cmdRoot.AddCommand(
cmdVersion,
)
// define flags
cmdRoot.Flags().StringVarP(
&cmd.RootPersistentDir,
"persistent-directory", "d",
"bridgedata",
"location of the root diretory used to store persistent data of the daemon of "+cmd.BlockchainInfo.Name,
)
cmdRoot.Flags().StringVar(
&cmd.RPCaddr,
"rpc-addr",
cmd.RPCaddr,
"which port the gateway listens on",
)
cmdRoot.Flags().StringVarP(
&cmd.BlockchainInfo.NetworkName,
"network", "n",
cmd.BlockchainInfo.NetworkName,
"the name of the tfchain network to connect to {standard,testnet,devnet}",
)
cli.NetAddressArrayFlagVar(
cmdRoot.Flags(),
&cmd.BootstrapPeers,
"bootstrap-peers",
"overwrite the bootstrap peers to use, instead of using the default bootstrap peers",
)
// bridge flags
cmdRoot.Flags().StringVar(
&cmd.EthNetworkName,
"ethnetwork", "",
"The ethereum network, {main, rinkeby, ropsten}, defaults to the TFT-linked network",
)
cmdRoot.Flags().Uint16Var(
&cmd.EthPort,
"ethport", 3003,
"port for the ethereum deamon",
)
// bridge account
cmdRoot.Flags().StringVar(
&cmd.accJSON,
"account-json", "",
"the path to an account file. If set, the specified account will be loaded",
)
cmdRoot.Flags().StringVar(
&cmd.accPass,
"account-password", "",
"Password for the bridge account",
)
cmdRoot.Flags().IntVarP(
&cmd.EthLog,
"ethereum-log-lvl", "e", 3,
"Log lvl for the ethereum logger",
)
cmdRoot.Flags().StringVar(
&cmd.ContractAddress,
"contract-address", "",
"Use a custom contract",
)
// execute logic
if err := cmdRoot.Execute(); err != nil {
os.Exit(1)
}
}