Skip to content
Permalink
Browse files

Disable eth service by default

  • Loading branch information...
tubackkhoa committed Jan 9, 2019
1 parent 168f5fa commit 54dc6a7c8a5ad5e9e01dc62fc9b44687a4880251
Showing with 75 additions and 175 deletions.
  1. +75 −161 OrderBook/main.go
  2. +0 −9 OrderBook/protocol/orderbook_api.go
  3. +0 −5 OrderBook/protocol/protocol.go
@@ -45,24 +45,21 @@ var (
// get the incoming message
msgC = make(chan interface{})

prompt *promptui.Select
commands []terminal.Command

prompt *promptui.Select
commands []terminal.Command
genesisPath string
mining bool
orderbookEngine *orderbook.Engine
)

func initPrompt(privateKeyName string) {

// default value for node2 if using keystore1 and vice versa
var nodeaddr, publickey string
var nodeaddr string
if privateKeyName == "keystore1" {
// bzzaddr = "0x9984c9556ca87842c4ceb839518cd3648dc495d579f7af7f9ba49989bc207346"
nodeaddr = "enode://ce24c4f944a0a3614b691d839a6a89339d17abac3d69c0d24e806db45d1bdbe7afa53c02136e5ad952f43e6e7285cd3971e367d8789f4eb7306770f5af78755d@127.0.0.1:30101?discport=0"
publickey = "0x04ce24c4f944a0a3614b691d839a6a89339d17abac3d69c0d24e806db45d1bdbe7afa53c02136e5ad952f43e6e7285cd3971e367d8789f4eb7306770f5af78755d"
} else {
// bzzaddr = "0x1bb065aa5e7997efc322a0223b62cd4ca218ce9f51c1e85bf9bd429f9265a3d7"
nodeaddr = "enode://655b231711df566a1bbf8f62dd0abaad71a1baa2c4bc865cae1691431bff2d9185fb66c99b982e20fd0fd562ced2c1ced96bd3e1daba0235870dfce0663a3483@127.0.0.1:30100?discport=0"
publickey = "0x04655b231711df566a1bbf8f62dd0abaad71a1baa2c4bc865cae1691431bff2d9185fb66c99b982e20fd0fd562ced2c1ced96bd3e1daba0235870dfce0663a3483"
}

orderArguments := []terminal.Argument{
@@ -96,22 +93,9 @@ func initPrompt(privateKeyName string) {
Name: "addNode",
Arguments: []terminal.Argument{
{Name: "nodeaddr", Value: nodeaddr},
{Name: "publickey", Value: publickey},
},
Description: "Add node to seed",
},
// {
// Name: "updateBzz",
// Arguments: []terminal.Argument{
// {Name: "bzzaddr", Value: bzzaddr},
// {Name: "publickey", Value: publickey},
// },
// Description: "Associate swarm topic with public key",
// },
// {
// Name: "bzzAddr",
// Description: "Get Swarm address",
// },
{
Name: "nodeAddr",
Description: "Get Node address",
@@ -135,11 +119,12 @@ func init() {
Name: "start",
Action: func(c *cli.Context) error {
privateKeyName := path.Base(c.String("privateKey"))
mining = c.Bool("mining")
// init prompt
initPrompt(privateKeyName)
// must return export function
return Start(c.Int("p2pPort"), c.Int("httpPort"), c.Int("wsPort"), c.String("name"),
c.String("privateKey"), c.Bool("mining"))
c.String("privateKey"))
},
Flags: []cli.Flag{
cli.IntFlag{Name: "p2pPort, p1", Value: demo.P2pPort},
@@ -163,19 +148,19 @@ func main() {

}

func Start(p2pPort int, httpPort int, wsPort int, name string, privateKey string, mining bool) error {
func Start(p2pPort int, httpPort int, wsPort int, name string, privateKey string) error {

// start the program at other rtine
_, fileName, _, _ := runtime.Caller(1)
basePath := path.Dir(fileName)
privateKeyPath := path.Join(basePath, privateKey)
genesisPath := path.Join(basePath, "genesis.json")
genesisPath = path.Join(basePath, "genesis.json")
// privateKeyPath is from current folder where the file is running
demo.LogInfo("Connecting to pss websocket", "host", node.DefaultWSHost,
demo.LogInfo("Start node", "host", node.DefaultWSHost,
"p2pPort", p2pPort, "httpPort", httpPort, "wsPort", wsPort, "name",
name, "privateKey", privateKeyPath)

startup(p2pPort, httpPort, wsPort, name, privateKeyPath, genesisPath, mining)
startup(p2pPort, httpPort, wsPort, name, privateKeyPath)

// process command
fmt.Println("---------------Welcome to Orderbook over swarm testing---------------------")
@@ -215,20 +200,12 @@ func Start(p2pPort int, httpPort int, wsPort int, name string, privateKey string
demo.LogInfo("-> Add order", "payload", results)
// put message on channel
go processOrder(results)
// case "publicKey":
// demo.LogInfo(fmt.Sprintf("-> Public Key: %s\n", publicKey()))
// case "updateBzz":
// bzzaddr := results["bzzaddr"]
// // publickey := results["publickey"]
// demo.LogInfo(fmt.Sprintf("-> Add bzz: %s\n", bzzaddr))
// // updateBzz(bzzaddr, publickey)

case "addNode":
nodeaddr := results["nodeaddr"]
publickey := results["publickey"]
demo.LogInfo(fmt.Sprintf("-> Add node: %s\n", nodeaddr))
addNode(nodeaddr, publickey)
// case "bzzAddr":
// demo.LogInfo(fmt.Sprintf("-> BZZ Address: %s\n", bzzAddr()))
addNode(nodeaddr)

case "nodeAddr":
demo.LogInfo(fmt.Sprintf("-> Node Address: %s\n", nodeAddr()))

@@ -251,16 +228,8 @@ func shutdown() error {
return nil
}

// func updateBzz(bzzAddr string, publicKey string) error {
// rpcClient, err := thisNode.Attach()

// // Set Public key to associate with a particular Pss peer
// err = rpcClient.Call(nil, "pss_setPeerPublicKey", publicKey, protocol.OrderbookTopic, bzzAddr)
// return err
// }
func addNode(rawurl string) error {

func addNode(rawurl string, publicKey string) error {
// newNode, err := enode.ParseV4(rawurl)
newNode, err := discover.ParseNode(rawurl)
if err != nil {
demo.LogCrit("pass node addr fail", "err", err)
@@ -270,20 +239,6 @@ func addNode(rawurl string, publicKey string) error {
demo.LogInfo("add node", "node", newNode.String())
thisNode.Server().AddPeer(newNode)

// // if have protocol implemented
// if len(pssprotos) > 0 {
// nid := newNode.ID()
// p := p2p.NewPeer(nid, nid.String(), []p2p.Cap{})

// // add peer with its public key to this protocol on a topic and using asymetric cryptography
// pssprotos[0].AddPeer(p, protocol.OrderbookTopic, true, publicKey)

// if err != nil {
// demo.LogCrit("pss set pubkey fail", "err", err)
// }

// }

demo.LogInfo("Added node successfully!")
return nil
}
@@ -292,51 +247,76 @@ func nodeAddr() string {
return thisNode.Server().Self().String()
}

// func bzzAddr() string {
// // get the rpc clients
// rpcClient, err := thisNode.Attach()
// // get the recipient node's swarm overlay address
// var bzzAddr string
// err = rpcClient.Call(&bzzAddr, "pss_baseAddr")
// if err != nil {
// demo.LogCrit("pss get baseaddr fail", "err", err)
// }
// return bzzAddr
// }

// func publicKey() string {
// // get the publickeys
// var pubkey string
// rpcClient, err := thisNode.Attach()
// err = rpcClient.Call(&pubkey, "pss_getPublicKey")
// if err != nil {
// demo.LogCrit("pss get pubkey fail", "err", err)
// }
// return pubkey
// }

func processOrder(payload map[string]string) error {
// add order at this current node first
// get timestamp in milliseconds
payload["timestamp"] = strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
msg, err := protocol.NewOrderbookMsg(payload)
if err == nil {
// try to store into model, if success then process at local and broad cast
// err = orderbookEngine.ProcessOrder(msg)
// if err == nil {
trades, orderInBook := orderbookEngine.ProcessOrder(payload)
demo.LogInfo("Orderbook result", "Trade", trades, "OrderInBook", orderInBook)

// broad cast message
msgC <- msg
// }

}

return nil
}

func updateEthService() {
// make full node after start the node, then later register swarm service over that node
ethConfig, err := initGenesis(thisNode)
ethConfig.Etherbase = crypto.PubkeyToAddress(privkey.PublicKey)
if err != nil {
panic(err.Error())
}

// register ethservice with genesis block
utils.RegisterEthService(thisNode, ethConfig)

if err != nil {
demo.LogCrit("servicenode pss register fail", "err", err)
}

// config ethereum
var ethereum *eth.Ethereum
if err := thisNode.Service(&ethereum); err != nil {
demo.LogError(fmt.Sprintf("Ethereum service not running: %v", err))
}

// config ethereum gas price
ethereum.TxPool().SetGasPrice(ethConfig.GasPrice)

password := "123456789"
ks := thisNode.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
// import will create a keystore if not found
account, err := ks.ImportECDSA(privkey, password)
err = ks.Unlock(account, password)
if err != nil {
panic(err)
}

// if this node can mine
if mining {
miner := ethereum.Miner()
miner.Start(account.Address)
}
}

func updateExtraService(rpcapi []string) {

for _, api := range rpcapi {
if api == "eth" {
updateEthService()
}
}

}

// simple ping and receive protocol
func startup(p2pPort int, httpPort int, wsPort int, name string, privateKey string, genesisPath string, mining bool) {
func startup(p2pPort int, httpPort int, wsPort int, name string, privateKey string) {

var err error

@@ -345,10 +325,7 @@ func startup(p2pPort int, httpPort int, wsPort int, name string, privateKey stri

// register pss and orderbook service
rpcapi := []string{
"eth",
// "ssh",
// "personal",
// "pss",
// "eth",
"orderbook",
}
dataDir := fmt.Sprintf("%s%d", demo.DatadirPrefix, p2pPort)
@@ -365,92 +342,29 @@ func startup(p2pPort int, httpPort int, wsPort int, name string, privateKey stri
}

thisNode, err = demo.NewServiceNodeWithPrivateKeyAndDataDirAndProtocols(privkey, dataDir, p2pPort, httpPort, wsPort, protocolArr, rpcapi...)
// proto := protocol.NewProtocol(msgC, quitC, orderbookEngine)
// server := demo.NewServer(privateKey, name, *proto, httpPort)
// register normal service, protocol is for p2p, service is for rpc calls
err = thisNode.Register(protocol.NewService(orderbookEngine))
if err != nil {
demo.LogCrit(err.Error())
demo.LogCrit("Register orderbook service in servicenode failed", "err", err)
}

// make full node after start the node, then later register swarm service over that node
ethConfig, err := initGenesis(thisNode, genesisPath)
ethConfig.Etherbase = crypto.PubkeyToAddress(privkey.PublicKey)
if err != nil {
panic(err.Error())
demo.LogCrit(err.Error())
}

// register ethservice with genesis block
utils.RegisterEthService(thisNode, ethConfig)

// do we need to register whisper? maybe not
// sshConfig := whisperv6.DefaultConfig
// utils.RegisterShhService(thisNode, &sshConfig)

// register swarm service
// bzzURL := fmt.Sprintf("http://%s:%d", node.DefaultHTTPHost, bzzPort)

// signer := feed.NewGenericSigner(privkey)

// protocolSpecs := []*protocols.Spec{protocol.OrderbookProtocol}

// register the pss activated bzz services
// svc := demo.NewSwarmServiceWithProtocolAndPrivateKey(thisNode, bzzPort, protocolSpecs, protocolArr, &protocol.OrderbookTopic, &pssprotos, privkey)
// err = thisNode.Register(svc)

// thisNode.Server().Protocols = protocolArr

if err != nil {
demo.LogCrit("servicenode pss register fail", "err", err)
}
// register normal service, using bzz client internally
err = thisNode.Register(protocol.NewService(orderbookEngine))
if err != nil {
demo.LogCrit("Register orderbook service in servicenode failed", "err", err)
}
// extra service like eth, swarm need more work
updateExtraService(rpcapi)

// start the nodes
err = thisNode.Start()
if err != nil {
demo.LogCrit("servicenode start failed", "err", err)
}

// rpcClient, err := thisNode.Attach()
// // wait until the state of the swarm overlay network is ready
// ctx, cancel := context.WithTimeout(context.Background(), time.Second)
// defer cancel()
// err = demo.WaitHealthy(ctx, 1, rpcClient)
// if err != nil {
// demo.LogCrit("health check fail", "err", err)
// }
// time.Sleep(time.Second) // because the healthy does not work

// config ethereum
var ethereum *eth.Ethereum
if err := thisNode.Service(&ethereum); err != nil {
demo.LogError(fmt.Sprintf("Ethereum service not running: %v", err))
}

// config ethereum gas price
ethereum.TxPool().SetGasPrice(ethConfig.GasPrice)

password := "123456789"
ks := thisNode.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
// import will create a keystore if not found
account, err := ks.ImportECDSA(privkey, password)
err = ks.Unlock(account, password)
if err != nil {
panic(err)
}

// if this node can mine
if mining {
miner := ethereum.Miner()
miner.Start(account.Address)
}

}

// geth init genesis.json --datadir .datadir
func initGenesis(stack *node.Node, genesisPath string) (*eth.Config, error) {
func initGenesis(stack *node.Node) (*eth.Config, error) {
ethConfig := &eth.DefaultConfig
ethConfig.SyncMode = downloader.FullSync
ethConfig.SkipBcVersionCheck = true
@@ -93,12 +93,3 @@ func (api *OrderbookAPI) GetOrder(pairName, orderID string) map[string]string {
}
return result
}

// func (api *OrderbookAPI) UpdateOrders(coin string, signerAddress string, hexData, hexSignature string, time uint64, level uint8) error {

// epoch := lookup.Epoch{
// Time: time,
// Level: level,
// }
// return api.Engine.UpdateData(coin, signerAddress, epoch, hexData, hexSignature)
// }
Oops, something went wrong.

0 comments on commit 54dc6a7

Please sign in to comment.
You can’t perform that action at this time.