Skip to content

Commit

Permalink
Merge pull request #119 from hashcloak/patch-katzenmint
Browse files Browse the repository at this point in the history
Update katzenmint PKI
  • Loading branch information
sc0Vu authored Apr 27, 2022
2 parents d1b329c + 0e78c40 commit 28160a1
Show file tree
Hide file tree
Showing 16 changed files with 291 additions and 231 deletions.
5 changes: 3 additions & 2 deletions client/timer_queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package client

import (
"container/heap"
"fmt"
"sync"
"time"
Expand Down Expand Up @@ -72,7 +73,7 @@ func (a *TimerQueue) Remove(i Item) error {
defer a.Unlock()
if mo := a.priq.Peek(); mo != nil {
if mo.Value.(Item).Priority() == i.Priority() {
_ = a.priq.Pop()
_ = heap.Pop(a.priq)
if a.priq.Len() > 0 {
a.Signal()
}
Expand Down Expand Up @@ -114,7 +115,7 @@ func (a *TimerQueue) wakeupCh() chan struct{} {
// pop top item from queue and forward to next queue
func (a *TimerQueue) forward() {
a.Lock()
m := a.priq.Pop()
m := heap.Pop(a.priq)

a.Unlock()
if m == nil {
Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ require (
github.com/katzenpost/core v0.0.12
github.com/katzenpost/registration_client v0.0.1
github.com/prometheus/client_golang v1.8.0
github.com/spf13/cobra v1.4.0
github.com/spf13/viper v1.10.1
github.com/stretchr/testify v1.7.0
github.com/tendermint/tendermint v0.34.10
Expand All @@ -28,6 +29,8 @@ require (
gopkg.in/op/go-logging.v1 v1.0.0-20160211212156-b2cb9fa56473
)

require github.com/inconshreveable/mousetrap v1.0.0 // indirect

require (
git.schwanenlied.me/yawning/bsaes.git v0.0.0-20190320102049-26d1add596b6 // indirect
github.com/DataDog/zstd v1.4.1 // indirect
Expand Down
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ github.com/cosmos/iavl v0.15.3/go.mod h1:OLjQiAQ4fGD2KDZooyJG9yz+p2ao2IAYSbke8mV
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down Expand Up @@ -411,6 +412,7 @@ github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmK
github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 h1:vr3AYkKovP8uR8AvSGGUK1IDqRa5lAAvEkZG1LKaCRc=
Expand Down Expand Up @@ -670,6 +672,7 @@ github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik=
github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sagikazarmark/crypt v0.4.0/go.mod h1:ALv2SRj7GxYV4HO9elxH9nS6M9gW+xDNxqmyJ6RfDFM=
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
Expand Down Expand Up @@ -704,6 +707,8 @@ github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3
github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU=
github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE=
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q=
github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
Expand Down
2 changes: 1 addition & 1 deletion katzenmint/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ setup:

.PHONY: build
build:
go build -tags=$(GOTAGS) -ldflags '$(LD_FLAGS)' -o katzenmint cmd/katzenmint/katzenmint.go
go build -tags=$(GOTAGS) -ldflags '$(LD_FLAGS)' -o katzenmint cmd/katzenmint/*.go

.PHONY: build-docker
build-docker:
Expand Down
25 changes: 18 additions & 7 deletions katzenmint/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package katzenmint
import (
"crypto/ed25519"
"fmt"
"sort"

"github.com/hashcloak/Meson/katzenmint/config"
"github.com/hashcloak/Meson/katzenmint/s11n"
Expand Down Expand Up @@ -220,13 +221,22 @@ func (app *KatzenmintApplication) Query(rquery abcitypes.RequestQuery) (resQuery
}

func (app *KatzenmintApplication) InitChain(req abcitypes.RequestInitChain) abcitypes.ResponseInitChain {
for _, v := range req.Validators {
err := app.state.updateAuthority(nil, v)
if err != nil {
app.logger.Error("failed to update validators", "error", err)
if len(req.Validators) > 0 {

sort.Sort(abcitypes.ValidatorUpdates(req.Validators))

for _, v := range req.Validators {
err := app.state.updateAuthority(nil, v)
if err != nil {
app.logger.Error("failed to update validators", "error", err)
}
}
}
return abcitypes.ResponseInitChain{}
return abcitypes.ResponseInitChain{
// ConsensusParams: req.ConsensusParams,
Validators: req.Validators,
// AppHash: appHash,
}
}

// Track the block hash and header information
Expand All @@ -253,8 +263,9 @@ func (app *KatzenmintApplication) BeginBlock(req abcitypes.RequestBeginBlock) ab

// Update validators
func (app *KatzenmintApplication) EndBlock(req abcitypes.RequestEndBlock) abcitypes.ResponseEndBlock {
// will there be race condition?
return abcitypes.ResponseEndBlock{ValidatorUpdates: app.state.validatorUpdates}
return abcitypes.ResponseEndBlock{
ValidatorUpdates: app.state.validatorUpdates,
}
}

// TODO: state sync connection
Expand Down
214 changes: 2 additions & 212 deletions katzenmint/cmd/katzenmint/katzenmint.go
Original file line number Diff line number Diff line change
@@ -1,224 +1,14 @@
package main

import (
//"errors"

"context"
"encoding/binary"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"

katzenmint "github.com/hashcloak/Meson/katzenmint"
kcfg "github.com/hashcloak/Meson/katzenmint/config"
"github.com/katzenpost/core/crypto/eddsa"
"github.com/spf13/viper"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
tmflags "github.com/tendermint/tendermint/libs/cli/flags"
"github.com/tendermint/tendermint/libs/log"
nm "github.com/tendermint/tendermint/node"
"github.com/tendermint/tendermint/p2p"
"github.com/tendermint/tendermint/privval"
"github.com/tendermint/tendermint/proxy"
"github.com/tendermint/tendermint/rpc/client/http"
dbm "github.com/tendermint/tm-db"
)

var (
configFile string
)

func readConfig(configFile string) (config *cfg.Config, err error) {
config = cfg.DefaultConfig()
config.SetRoot(filepath.Dir(filepath.Dir(configFile)))
viper.SetConfigFile(configFile)
if err = viper.ReadInConfig(); err != nil {
err = fmt.Errorf("viper failed to read config file: %w", err)
return
}
if err = viper.Unmarshal(config); err != nil {
err = fmt.Errorf("viper failed to unmarshal config: %w", err)
return
}
if err = config.ValidateBasic(); err != nil {
err = fmt.Errorf("config is invalid: %w", err)
return
}
return
}

func getRpcAddresses(config *cfg.Config) []string {
var rpcAddr []string
peers := append(
strings.Split(config.P2P.PersistentPeers, ","),
strings.Split(config.P2P.Seeds, ",")...,
)
for _, element := range peers {
element = strings.Trim(element, " ")
if element == "" {
continue
}
parsed := strings.Split(element, "@")
ipAddr := strings.Split(parsed[len(parsed)-1], ":")[0]
rpcAddr = append(rpcAddr, "tcp://"+ipAddr+":26657")
}
return rpcAddr
}

func joinNetwork(config *cfg.Config) error {
// connect to peers
var rpc *http.HTTP
var err error
for _, addr := range getRpcAddresses(config) {
rpc, err = http.New(addr, "/websocket")
if err != nil {
fmt.Printf("%v\n", err)
} else {
break
}
}
if rpc == nil {
return fmt.Errorf("cannot connect and broadcast to peers")
}

// load keys
pv := privval.LoadFilePV(
config.PrivValidatorKeyFile(),
config.PrivValidatorStateFile(),
)
privKey := new(eddsa.PrivateKey)
err = privKey.FromBytes(pv.Key.PrivKey.Bytes())
if err != nil {
return err
}

// prepare AddAuthority transaction
raw, err := katzenmint.EncodeJson(katzenmint.Authority{
Auth: config.Moniker,
Power: 1,
PubKey: pv.Key.PubKey.Bytes(),
KeyType: pv.Key.PubKey.Type(),
})
if err != nil {
return err
}
info, err := rpc.ABCIInfo(context.Background())
if err != nil {
return err
}
epoch, _ := binary.Uvarint(katzenmint.DecodeHex(info.Response.Data))
tx, err := katzenmint.FormTransaction(katzenmint.AddNewAuthority, epoch, string(raw), privKey)
if err != nil {
return err
}

// post transaction
resp, err := rpc.BroadcastTxSync(context.Background(), tx)
if err != nil {
return err
}
if resp.Code != abci.CodeTypeOK {
return fmt.Errorf("broadcast tx error: %v", resp.Log)
}
return nil
}

func newTendermint(app abci.Application, config *cfg.Config, logger log.Logger) (node *nm.Node, err error) {

// read private validator
pv := privval.LoadFilePV(
config.PrivValidatorKeyFile(),
config.PrivValidatorStateFile(),
)

// read node key
var nodeKey *p2p.NodeKey
if nodeKey, err = p2p.LoadNodeKey(config.NodeKeyFile()); err != nil {
return nil, fmt.Errorf("failed to load node's key: %w", err)
}

// create node
node, err = nm.NewNode(
config,
pv,
nodeKey,
proxy.NewLocalClientCreator(app),
nm.DefaultGenesisDocProviderFunc(config),
nm.DefaultDBProvider,
nm.DefaultMetricsProvider(config.Instrumentation),
logger)
if err != nil {
return nil, fmt.Errorf("failed to create new Tendermint node: %w", err)
}

return node, nil
}

func init() {
flag.StringVar(&configFile, "config", "katzenmint.toml", "Path to katzenmint.toml")
flag.Parse()
}

func main() {
kConfig, err := kcfg.LoadFile(configFile)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err)
os.Exit(1)
}
config, err := readConfig(kConfig.TendermintConfigPath)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
db, err := dbm.NewDB("katzenmint_db", dbm.BadgerDBBackend, kConfig.DBPath)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open badger db: %v\ntry running with -tags badgerdb\n", err)
os.Exit(1)
}
defer db.Close()

logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
if logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel); err != nil {
fmt.Fprintf(os.Stderr, "failed to parse log level: %v\n", err)
os.Exit(1)
}

app := katzenmint.NewKatzenmintApplication(kConfig, db, logger)
node, err := newTendermint(app, config, logger)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(2)
}

if !kConfig.Membership {
err = joinNetwork(config)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(2)
}
kConfig.Membership = true
err = kcfg.WriteConfigFile(configFile, kConfig)
if err != nil {
fmt.Fprintf(os.Stderr, "error saving config: %v\n", err)
}
}

if err = node.Start(); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(2)
}
defer func() {
_ = node.Stop()
node.Wait()
}()

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
os.Exit(0)
}
Loading

0 comments on commit 28160a1

Please sign in to comment.