From 7a38671da3c5eedbb4b173ba3c765d12ffbedeb8 Mon Sep 17 00:00:00 2001 From: Kay Date: Sat, 25 Nov 2023 13:53:59 +0000 Subject: [PATCH 01/30] feat: add is synced field to peer-info command --- client/client.go | 9 +++++++++ discord/discord.go | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/client/client.go b/client/client.go index d6e4ec4..8865bb8 100644 --- a/client/client.go +++ b/client/client.go @@ -126,6 +126,15 @@ func (c *Client) LastBlockTime() (uint32, error) { return lastBlockTime.BlockTime, err } +func (c *Client) GetNodeInfo() (*pactus.GetNodeInfoResponse, error) { + info, err := c.networkClient.GetNodeInfo(context.Background(), &pactus.GetNodeInfoRequest{}) + if err != nil { + return &pactus.GetNodeInfoResponse{}, err + } + + return info, err +} + func (c *Client) Close() error { return c.conn.Close() } diff --git a/discord/discord.go b/discord/discord.go index 2705232..13da560 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -143,11 +143,30 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } + notSyncedMsg := "this peer is not synced with network, gRPC is disabled or doesn't have public IP address." + syncedMsg := "**this peer is synced with network**" + + isSynced := notSyncedMsg + c, err := client.NewClient(strings.Split(peerInfo.Address, "/")[2] + ":50051") + if err != nil { + isSynced = notSyncedMsg + } + lastBlockTime, err := c.LastBlockTime() + if err != nil { + isSynced = notSyncedMsg + } + currentTime := time.Now().Unix() + + if (uint32(currentTime) - lastBlockTime) < 15 { + isSynced = syncedMsg + } + msg := p.Sprintf("Peer info\n") msg += p.Sprintf("Peer ID: %v\n", peerID) msg += p.Sprintf("IP address: %v\n", peerInfo.Address) msg += p.Sprintf("Agent: %v\n", peerInfo.Agent) msg += p.Sprintf("Moniker: %v\n", peerInfo.Moniker) + msg += p.Sprintf("IsSynced: %v\n", isSynced) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } From ec6dfee742ad3dcf1244f08033f6b2619ff2446c Mon Sep 17 00:00:00 2001 From: Kay Date: Sat, 25 Nov 2023 13:58:45 +0000 Subject: [PATCH 02/30] chore: change user grpc port --- discord/discord.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/discord/discord.go b/discord/discord.go index 13da560..2fafccc 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -147,7 +147,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { syncedMsg := "**this peer is synced with network**" isSynced := notSyncedMsg - c, err := client.NewClient(strings.Split(peerInfo.Address, "/")[2] + ":50051") + c, err := client.NewClient(strings.Split(peerInfo.Address, "/")[2] + ":50052") if err != nil { isSynced = notSyncedMsg } From 1d6176c6e8713556a3f95d2998a5eee6be148bf1 Mon Sep 17 00:00:00 2001 From: Kay Date: Sat, 2 Dec 2023 13:43:42 +0000 Subject: [PATCH 03/30] fix: wrong data in network status --- discord/discord.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index 2fafccc..9860954 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -325,8 +325,8 @@ func (b *Bot) networkInfo() string { } msg += "\nThe following are the currentl statistics:\n" msg += fmt.Sprintf("Network started at : %v\n", time.UnixMilli(nodes.StartedAt*1000).Format("02/01/2006, 15:04:05")) - msg += fmt.Sprintf("Total bytes sent : %v\n", nodes.TotalSentBytes) - msg += fmt.Sprintf("Total received bytes : %v\n", nodes.TotalReceivedBytes) + msg += fmt.Sprintf("Total bytes sent : %v\n", uint32(nodes.TotalSentBytes)) + msg += fmt.Sprintf("Total received bytes : %v\n", uint32(nodes.TotalReceivedBytes)) msg += fmt.Sprintf("Number of peer nodes: %v\n", len(nodes.Peers)) // check block height blockchainInfo, err := b.cm.GetBlockchainInfo() From ff35cb8f580e8f643c918f535e84dbdbc4bb6f73 Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 7 Dec 2023 12:18:14 +0000 Subject: [PATCH 04/30] feat: referral system (#9) --- cmd/app.go | 9 +++- config/config.go | 16 +++--- discord/discord.go | 100 ++++++++++++++++++++++++++++++++++- discord/referral.go | 125 ++++++++++++++++++++++++++++++++++++++++++++ go.mod | 1 + go.sum | 8 +++ wallet/wallet.go | 2 +- 7 files changed, 250 insertions(+), 11 deletions(-) create mode 100644 discord/referral.go diff --git a/cmd/app.go b/cmd/app.go index 3ed0d5f..57f6b5d 100644 --- a/cmd/app.go +++ b/cmd/app.go @@ -35,8 +35,15 @@ func main() { return } + // load list of validators already received faucet + rs, err := discord.LoadReferralData(cfg) + if err != nil { + log.Println(err) + return + } + ///start discord bot - bot, err := discord.Start(cfg, w, ss) + bot, err := discord.Start(cfg, w, ss, rs) if err != nil { log.Printf("could not start discord bot: %v\n", err) return diff --git a/config/config.go b/config/config.go index 2949c99..3c7ef45 100644 --- a/config/config.go +++ b/config/config.go @@ -8,13 +8,15 @@ import ( ) type Config struct { - DiscordToken string `json:"discord_token"` - WalletPath string `json:"wallet_path"` - WalletPassword string `json:"wallet_password"` - Servers []string `json:"servers"` - FaucetAddress string `json:"faucet_address"` - FaucetAmount float64 `json:"faucet_amount"` - ValidatorDataPath string `json:"validator_data_path"` + DiscordToken string `json:"discord_token"` + WalletPath string `json:"wallet_path"` + WalletPassword string `json:"wallet_password"` + Servers []string `json:"servers"` + FaucetAddress string `json:"faucet_address"` + FaucetAmount float64 `json:"faucet_amount"` + ReferralerStakeAmount float64 `json:"referraler_stake_amount"` // who get faucet + ValidatorDataPath string `json:"validator_data_path"` + ReferralDataPath string `json:"referral_data_path"` } func Load(path string) (*Config, error) { diff --git a/discord/discord.go b/discord/discord.go index 9860954..4d9b4d5 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -11,6 +11,7 @@ import ( "github.com/kehiy/RoboPac/config" "github.com/kehiy/RoboPac/wallet" "github.com/libp2p/go-libp2p/core/peer" + gonanoid "github.com/matoous/go-nanoid/v2" "github.com/pactus-project/pactus/crypto" "github.com/pactus-project/pactus/util" pactus "github.com/pactus-project/pactus/www/grpc/gen/go" @@ -23,13 +24,14 @@ type Bot struct { faucetWallet *wallet.Wallet cfg *config.Config store *SafeStore + referralStore *ReferralStore cm *client.Mgr } // guildID: "795592769300987944" -func Start(cfg *config.Config, w *wallet.Wallet, ss *SafeStore) (*Bot, error) { +func Start(cfg *config.Config, w *wallet.Wallet, ss *SafeStore, rs *ReferralStore) (*Bot, error) { cm := client.NewClientMgr() for _, s := range cfg.Servers { @@ -171,6 +173,97 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } + if strings.ToLower(m.Content) == "my-referral" { + referrals := b.referralStore.GetAllReferrals() + for _, r := range referrals { + if r.DiscordID == m.Author.ID { + msg := fmt.Sprintf("Your referral data:\nPoints: %v\nCode: ```%v```\n", r.Points, r.ReferralCode) + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } + } + + referralCode, err := gonanoid.New(10) + if err != nil { + msg := "can't generate referral code, please try again later." + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } + + err = b.referralStore.NewReferral(m.Author.ID, m.Author.Username, referralCode) + if err != nil { + msg := "can't generate referral code, please try again later." + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } + + msg := fmt.Sprintf("Your referral data:\nPoints: %v\nCode: ```%v```\n", 0, referralCode) + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } + + if strings.Contains(strings.ToLower(m.Content), "faucet-referral") { + trimmedPrefix := strings.TrimPrefix(strings.ToLower(m.Content), "faucet-referral") + + Params := strings.Split(trimmedPrefix, " ") + if len(Params) != 2 { + msg := p.Sprintf("*Invalid* parameters!") + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } + + address := strings.Trim(Params[0], " ") + referralCode := strings.Trim(Params[1], " ") + + peerID, pubKey, isValid, msg := b.validateInfo(address, m.Author.ID) + + msg = fmt.Sprintf("%v\ndiscord: %v\naddress: %v", + msg, m.Author.Username, address) + + if !isValid { + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } + + // validate referral. + _, found := b.referralStore.GetData(referralCode) + if !found { + msg := p.Sprintf("*Invalid* referral!") + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } + + if pubKey != "" { + // check available balance + balance := b.faucetWallet.GetBalance() + if balance.Available < b.cfg.FaucetAmount { + _, _ = s.ChannelMessageSendReply(m.ChannelID, "Insufficient faucet balance. Try again later.", m.Reference()) + return + } + + amount := b.cfg.ReferralerStakeAmount + ok := b.referralStore.AddPoint(referralCode) + if !ok { + _, _ = s.ChannelMessageSendReply(m.ChannelID, "Can't update referral data. please try again later.", m.Reference()) + return + } + + // send faucet + txHashFaucet := b.faucetWallet.BondTransaction(pubKey, address, amount) + + if txHashFaucet != "" { + err := b.store.SetData(peerID, address, m.Author.Username, m.Author.ID, amount) + if err != nil { + log.Printf("error saving faucet information: %v\n", err) + } + + msg := p.Sprintf("%v %.4f test PACs is staked to %v successfully!", + m.Author.Username, amount, address) + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + } + } + } + if strings.Contains(strings.ToLower(m.Content), "faucet") { trimmedPrefix := strings.TrimPrefix(strings.ToLower(m.Content), "faucet") // faucet message must contain address/public-key @@ -240,8 +333,11 @@ func help(s *discordgo.Session, m *discordgo.MessageCreate) { "To see the faucet account balance, simply type: `balance`\n" + "To see the faucet address, simply type: `address`\n" + "To get network information, simply type: `network`\n" + + "To get network health status, simply type: `health`\n" + "To get peer information, simply type: `peer-info [validator address]`\n" + - "To request faucet for test network: simply post `faucet [validator address]`.", + "To get your referral information, simply type: `my-referral`\n" + + "To request faucet for test network *with referral code*: simply type `faucet-referral [validator address] [referral code]`\n" + + "To request faucet for test network: simply type `faucet [validator address]`.", Fields: []*discordgo.MessageEmbedField{ { Name: "Example of requesting `faucet` ", diff --git a/discord/referral.go b/discord/referral.go new file mode 100644 index 0000000..2bfd36b --- /dev/null +++ b/discord/referral.go @@ -0,0 +1,125 @@ +package discord + +import ( + "fmt" + "log" + "os" + "sync" + + "github.com/kehiy/RoboPac/config" +) + +type Referral struct { + ReferralCode string `json:"referral_code"` + Points int `json:"points"` + DiscordName string `json:"discord_name"` + DiscordID string `json:"discord_id"` +} + +// SafeStore is a thread-safe cache. +type ReferralStore struct { + syncMap *sync.Map + cfg *config.Config +} + +func LoadReferralData(cfg *config.Config) (*ReferralStore, error) { + file, err := os.ReadFile(cfg.ReferralDataPath) + if err != nil { + log.Printf("error loading validator data: %v", err) + return nil, fmt.Errorf("error loading data file: %w", err) + } + if len(file) == 0 { + rs := &ReferralStore{ + syncMap: &sync.Map{}, + cfg: cfg, + } + return rs, nil + } + + data, err := unmarshalJSON(file) + if err != nil { + log.Printf("error unmarshalling validator data: %v", err) + return nil, fmt.Errorf("error unmarshalling validator data: %w", err) + } + rs := &ReferralStore{ + syncMap: data, + cfg: cfg, + } + return rs, nil +} + +// SetData Set a given value to the data storage. +func (rs *ReferralStore) NewReferral(discordId, discordName, referralCode string) error { + rs.syncMap.Store(referralCode, &Referral{ + Points: 0, + DiscordName: discordName, + ReferralCode: referralCode, + DiscordID: discordId, + }) + // save record + data, err := marshalJSON(rs.syncMap) + if err != nil { + log.Printf("error marshalling validator data file: %v", err) + return fmt.Errorf("error marshalling validator data file: %w", err) + } + if err := os.WriteFile(rs.cfg.ReferralDataPath, data, 0o600); err != nil { + log.Printf("failed to write to %s: %v", rs.cfg.ReferralDataPath, err) + return fmt.Errorf("failed to write to %s: %w", rs.cfg.ReferralDataPath, err) + } + return nil +} + +// GetData retrieves the given key from the storage. +func (rs *ReferralStore) GetData(code string) (*Referral, bool) { + entry, found := rs.syncMap.Load(code) + if !found { + return nil, false + } + referral := entry.(*Referral) + return referral, true +} + +// GetAllReferrals retrieves all referrals in store. +func (rs *ReferralStore) GetAllReferrals() []*Referral { + result := []*Referral{} + + rs.syncMap.Range(func(key, value any) bool { + referral, ok := value.(*Referral) + if !ok { + return true + } + result = append(result, referral) + return true + }) + + return result +} + +// AddPoint add one point for a referral. +func (rs *ReferralStore) AddPoint(code string) bool { + entry, found := rs.syncMap.Load(code) + if !found { + return false + } + + if found { + referral := entry.(*Referral) + referral.Points++ + rs.syncMap.Store(referral.ReferralCode, referral) + return true + } + + // save record + data, err := marshalJSON(rs.syncMap) + if err != nil { + log.Printf("error marshalling validator data file: %v", err) + return false + } + + if err := os.WriteFile(rs.cfg.ReferralDataPath, data, 0o600); err != nil { + log.Printf("failed to write to %s: %v", rs.cfg.ReferralDataPath, err) + return false + } + + return false +} diff --git a/go.mod b/go.mod index 16d4e9d..8c6a4b8 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/bwmarrin/discordgo v0.27.1 github.com/k0kubun/pp v3.0.1+incompatible github.com/libp2p/go-libp2p v0.31.0 + github.com/matoous/go-nanoid/v2 v2.0.0 github.com/pactus-project/pactus v0.17.0 github.com/yudai/pp v2.0.1+incompatible golang.org/x/text v0.13.0 diff --git a/go.sum b/go.sum index 6cc70c0..a906318 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,6 @@ github.com/bwmarrin/discordgo v0.27.1 h1:ib9AIc/dom1E/fSIulrBwnez0CToJE113ZGt4HoliGY= github.com/bwmarrin/discordgo v0.27.1/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= @@ -37,6 +38,9 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/libp2p/go-libp2p v0.31.0 h1:LFShhP8F6xthWiBBq3euxbKjZsoRajVEyBS9snfHxYg= github.com/libp2p/go-libp2p v0.31.0/go.mod h1:W/FEK1c/t04PbRH3fA9i5oucu5YcgrG0JVoBWT1B7Eg= +github.com/matoous/go-nanoid v1.5.0/go.mod h1:zyD2a71IubI24efhpvkJz+ZwfwagzgSO6UNiFsZKN7U= +github.com/matoous/go-nanoid/v2 v2.0.0 h1:d19kur2QuLeHmJBkvYkFdhFBzLoo1XVm2GgTpL+9Tj0= +github.com/matoous/go-nanoid/v2 v2.0.0/go.mod h1:FtS4aGPVfEkxKxhdWPAspZpZSh1cOjtM7Ej/So3hR0g= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= @@ -66,6 +70,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= @@ -113,6 +119,8 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= lukechampine.com/blake3 v1.2.1 h1:YuqqRuaqsGV71BV/nm9xlI0MKUv4QC54jQnBChWbGnI= diff --git a/wallet/wallet.go b/wallet/wallet.go index 9eb86d9..c860d21 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -43,7 +43,7 @@ func Open(cfg *config.Config) *Wallet { func (w *Wallet) BondTransaction(pubKey, toAddress string, amount float64) string { opts := []pwallet.TxOption{ pwallet.OptionFee(util.CoinToChange(0)), - pwallet.OptionMemo("faucet from PactusBot"), + pwallet.OptionMemo("Faucet from PactusBot"), } tx, err := w.wallet.MakeBondTx(w.address, toAddress, pubKey, util.CoinToChange(amount), opts...) From 256cddbb2122c51dad4694af98ce0796dbc9ed1e Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 7 Dec 2023 14:43:55 +0000 Subject: [PATCH 05/30] chore: fix get all referrals --- discord/referral.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/discord/referral.go b/discord/referral.go index 2bfd36b..563e00b 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -84,12 +84,12 @@ func (rs *ReferralStore) GetAllReferrals() []*Referral { result := []*Referral{} rs.syncMap.Range(func(key, value any) bool { - referral, ok := value.(*Referral) - if !ok { + referral, _ := value.(*Referral) + result = append(result, referral) + if value == nil { return true } - result = append(result, referral) - return true + return false }) return result From 2117aa883103d701341037eacfc645fa9e22b5d0 Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 7 Dec 2023 14:47:19 +0000 Subject: [PATCH 06/30] chore: fix get all referrals --- discord/discord.go | 2 +- discord/referral.go | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index 4d9b4d5..e379d60 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -49,7 +49,7 @@ func Start(cfg *config.Config, w *wallet.Wallet, ss *SafeStore, rs *ReferralStor log.Printf("error creating Discord session: %v", err) return nil, err } - bot := &Bot{cfg: cfg, discordSession: dg, faucetWallet: w, store: ss, cm: cm} + bot := &Bot{cfg: cfg, discordSession: dg, faucetWallet: w, store: ss, cm: cm, referralStore: rs} // Register the messageCreate func as a callback for MessageCreate events. dg.AddHandler(bot.messageHandler) diff --git a/discord/referral.go b/discord/referral.go index 563e00b..7c56a8c 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -86,10 +86,7 @@ func (rs *ReferralStore) GetAllReferrals() []*Referral { rs.syncMap.Range(func(key, value any) bool { referral, _ := value.(*Referral) result = append(result, referral) - if value == nil { - return true - } - return false + return value == nil }) return result From 960718b34bd355b537d22a7c8221ee15bdefde74 Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 7 Dec 2023 14:53:12 +0000 Subject: [PATCH 07/30] chore: fix get all referrals --- Makefile | 2 +- discord/referral.go | 31 ++++++++++++++++++++++++++++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 102d43c..3fe8035 100644 --- a/Makefile +++ b/Makefile @@ -31,6 +31,6 @@ check: golangci-lint run --build-tags "${BUILD_TAG}" --timeout=20m0s ### building -build: +build-discord-bot: go build -o build/main cmd/app.go \ No newline at end of file diff --git a/discord/referral.go b/discord/referral.go index 7c56a8c..509c2af 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -1,6 +1,7 @@ package discord import ( + "encoding/json" "fmt" "log" "os" @@ -36,7 +37,7 @@ func LoadReferralData(cfg *config.Config) (*ReferralStore, error) { return rs, nil } - data, err := unmarshalJSON(file) + data, err := unmarshalReferralJSON(file) if err != nil { log.Printf("error unmarshalling validator data: %v", err) return nil, fmt.Errorf("error unmarshalling validator data: %w", err) @@ -57,7 +58,7 @@ func (rs *ReferralStore) NewReferral(discordId, discordName, referralCode string DiscordID: discordId, }) // save record - data, err := marshalJSON(rs.syncMap) + data, err := marshaReferralJSON(rs.syncMap) if err != nil { log.Printf("error marshalling validator data file: %v", err) return fmt.Errorf("error marshalling validator data file: %w", err) @@ -107,7 +108,7 @@ func (rs *ReferralStore) AddPoint(code string) bool { } // save record - data, err := marshalJSON(rs.syncMap) + data, err := marshaReferralJSON(rs.syncMap) if err != nil { log.Printf("error marshalling validator data file: %v", err) return false @@ -120,3 +121,27 @@ func (rs *ReferralStore) AddPoint(code string) bool { return false } + +func marshaReferralJSON(m *sync.Map) ([]byte, error) { + tmpMap := make(map[string]*Validator) + + m.Range(func(k, v interface{}) bool { + tmpMap[k.(string)] = v.(*Validator) + return true + }) + return json.MarshalIndent(tmpMap, " ", " ") +} + +func unmarshalReferralJSON(data []byte) (*sync.Map, error) { + var tmpMap map[string]*Validator + m := &sync.Map{} + + if err := json.Unmarshal(data, &tmpMap); err != nil { + return m, err + } + + for key, value := range tmpMap { + m.Store(key, value) + } + return m, nil +} From e0699ada37a3245fc9ccd1223752f76751c6d7da Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 7 Dec 2023 14:54:54 +0000 Subject: [PATCH 08/30] chore: fix get all referrals --- discord/referral.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/discord/referral.go b/discord/referral.go index 509c2af..c7dda65 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -123,17 +123,17 @@ func (rs *ReferralStore) AddPoint(code string) bool { } func marshaReferralJSON(m *sync.Map) ([]byte, error) { - tmpMap := make(map[string]*Validator) + tmpMap := make(map[string]*Referral) m.Range(func(k, v interface{}) bool { - tmpMap[k.(string)] = v.(*Validator) + tmpMap[k.(string)] = v.(*Referral) return true }) return json.MarshalIndent(tmpMap, " ", " ") } func unmarshalReferralJSON(data []byte) (*sync.Map, error) { - var tmpMap map[string]*Validator + var tmpMap map[string]*Referral m := &sync.Map{} if err := json.Unmarshal(data, &tmpMap); err != nil { From 8de206b4e33784d4049c30038633fdf7db67eb6b Mon Sep 17 00:00:00 2001 From: Kay Date: Fri, 8 Dec 2023 10:34:54 +0000 Subject: [PATCH 09/30] fix: faucet referral command parsing --- discord/discord.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index e379d60..4c476ad 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -203,7 +203,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { } if strings.Contains(strings.ToLower(m.Content), "faucet-referral") { - trimmedPrefix := strings.TrimPrefix(strings.ToLower(m.Content), "faucet-referral") + trimmedPrefix := strings.TrimPrefix(m.Content, "faucet-referral ") Params := strings.Split(trimmedPrefix, " ") if len(Params) != 2 { @@ -212,8 +212,8 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } - address := strings.Trim(Params[0], " ") - referralCode := strings.Trim(Params[1], " ") + address := Params[0] + referralCode := Params[1] peerID, pubKey, isValid, msg := b.validateInfo(address, m.Author.ID) From 76a89324427a324677e0f9376ab5a20f27c35509 Mon Sep 17 00:00:00 2001 From: Kay Date: Fri, 8 Dec 2023 13:58:04 +0000 Subject: [PATCH 10/30] fix: referral codes --- discord/discord.go | 2 +- discord/referral.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index 4c476ad..e3340d4 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -183,7 +183,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { } } - referralCode, err := gonanoid.New(10) + referralCode, err := gonanoid.Generate("0123456789", 6) if err != nil { msg := "can't generate referral code, please try again later." _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) diff --git a/discord/referral.go b/discord/referral.go index c7dda65..946e372 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -87,7 +87,7 @@ func (rs *ReferralStore) GetAllReferrals() []*Referral { rs.syncMap.Range(func(key, value any) bool { referral, _ := value.(*Referral) result = append(result, referral) - return value == nil + return true }) return result From 73fe448c79d2ca9c149e0e8e66aac1365ba6121e Mon Sep 17 00:00:00 2001 From: Kay Date: Fri, 8 Dec 2023 18:25:32 +0000 Subject: [PATCH 11/30] fix: retuen in referral command --- discord/discord.go | 1 + 1 file changed, 1 insertion(+) diff --git a/discord/discord.go b/discord/discord.go index e3340d4..e80f60a 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -260,6 +260,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { msg := p.Sprintf("%v %.4f test PACs is staked to %v successfully!", m.Author.Username, amount, address) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return } } } From b8db4970834c3c61c5e8f1d9ac81e9bf32043628 Mon Sep 17 00:00:00 2001 From: Kay Date: Mon, 11 Dec 2023 16:04:01 +0000 Subject: [PATCH 12/30] chore: more detail on my-referral command result --- discord/discord.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index e80f60a..2b89f79 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -177,7 +177,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { referrals := b.referralStore.GetAllReferrals() for _, r := range referrals { if r.DiscordID == m.Author.ID { - msg := fmt.Sprintf("Your referral data:\nPoints: %v\nCode: ```%v```\n", r.Points, r.ReferralCode) + msg := fmt.Sprintf("Your referral data:\nPoints: %v (%v tPACs)\nCode: ```%v```\n", r.Points, (r.Points * 10), r.ReferralCode) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -197,7 +197,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } - msg := fmt.Sprintf("Your referral data:\nPoints: %v\nCode: ```%v```\n", 0, referralCode) + msg := fmt.Sprintf("Your referral data:\nPoints: %v (%v tPACs)\nCode: ```%v```\n", 0, 0, referralCode) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } From 919e2eda1d775d377827e02691e5d531e04d77e0 Mon Sep 17 00:00:00 2001 From: Kay Date: Sun, 17 Dec 2023 12:57:28 +0000 Subject: [PATCH 13/30] fix: accept message only from pactus server --- discord/discord.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/discord/discord.go b/discord/discord.go index 2b89f79..18795f5 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -82,6 +82,11 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } + // Ignore messages which is not from accepted channels + if m.GuildID != "795592769300987944" { + return + } + if strings.ToLower(m.Content) == "help" { help(s, m) return From c22df68ec01da166e6142d45d1e13d1af8da1c8a Mon Sep 17 00:00:00 2001 From: Kay Date: Sun, 17 Dec 2023 13:54:16 +0000 Subject: [PATCH 14/30] fix: only first validator will get stake faucet --- client/client_mgr.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/client/client_mgr.go b/client/client_mgr.go index 5161b0e..02ba571 100644 --- a/client/client_mgr.go +++ b/client/client_mgr.go @@ -96,10 +96,13 @@ func (cm *Mgr) GetPeerInfo(address string) (*pactus.PeerInfo, *bls.PublicKey, er if networkInfo != nil { for _, p := range networkInfo.Peers { - for _, key := range p.ConsensusKeys { + for i, key := range p.ConsensusKeys { pub, _ := bls.PublicKeyFromString(key) if pub != nil { if pub.ValidatorAddress().String() == address { + if i != 0 { + return nil, nil, errors.New("please enter the first validator address") + } return p, pub, nil } } From bb6944dec6d597fc74fdafc481dd945354041355 Mon Sep 17 00:00:00 2001 From: b00f Date: Mon, 18 Dec 2023 01:59:39 +0800 Subject: [PATCH 15/30] feat: adding python module to get validator information (#10) --- .gitignore | 3 +- python/address.py | 66 +++++ python/bech32m.py | 137 ++++++++++ python/main.py | 61 +++++ python/network_pb2.py | 52 ++++ python/network_pb2_grpc.py | 99 +++++++ python/pactus/blockchain_pb2.py | 81 ++++++ python/pactus/blockchain_pb2_grpc.py | 363 ++++++++++++++++++++++++++ python/pactus/network_pb2.py | 52 ++++ python/pactus/network_pb2_grpc.py | 99 +++++++ python/pactus/transaction_pb2.py | 64 +++++ python/pactus/transaction_pb2_grpc.py | 264 +++++++++++++++++++ python/pactus/wallet_pb2.py | 46 ++++ python/pactus/wallet_pb2_grpc.py | 198 ++++++++++++++ python/public_key.py | 50 ++++ python/test.py | 15 ++ python/utils.py | 15 ++ 17 files changed, 1664 insertions(+), 1 deletion(-) create mode 100644 python/address.py create mode 100644 python/bech32m.py create mode 100644 python/main.py create mode 100644 python/network_pb2.py create mode 100644 python/network_pb2_grpc.py create mode 100644 python/pactus/blockchain_pb2.py create mode 100644 python/pactus/blockchain_pb2_grpc.py create mode 100644 python/pactus/network_pb2.py create mode 100644 python/pactus/network_pb2_grpc.py create mode 100644 python/pactus/transaction_pb2.py create mode 100644 python/pactus/transaction_pb2_grpc.py create mode 100644 python/pactus/wallet_pb2.py create mode 100644 python/pactus/wallet_pb2_grpc.py create mode 100644 python/public_key.py create mode 100644 python/test.py create mode 100644 python/utils.py diff --git a/.gitignore b/.gitignore index faacc4b..155658d 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,5 @@ pactus-* cmd/data/wallet.json cmd/data/config.json cmd/data/validators.json -cmd/bin \ No newline at end of file +cmd/bin +__pycache__ \ No newline at end of file diff --git a/python/address.py b/python/address.py new file mode 100644 index 0000000..8e9c075 --- /dev/null +++ b/python/address.py @@ -0,0 +1,66 @@ +import io +from enum import Enum +import utils + +# Address format: hrp + `1` + type + data + checksum + + +class AddressType(Enum): + Treasury = 0 + Validator = 1 + BLSAccount = 2 + + +AddressSize = 21 +TreasuryAddressString = "000000000000000000000000000000000000000000" +AddressHRP = "tpc" + + +class Address: + def __init__(self, address_type, data): + if len(data) != AddressSize - 1: + raise ValueError("Data must be 21 bytes long") + + self.data = bytearray() + self.data.append(address_type.value) + self.data.extend(data) + + @classmethod + def from_string(cls, text): + if text == TreasuryAddressString: + return bytes([0]) + + hrp, typ, data = utils.decode_to_base256_with_type(text) + if hrp != AddressHRP: + raise ValueError(f"Invalid HRP: {hrp}") + + typ = AddressType(typ) + if typ in (AddressType.Validator, AddressType.BLSAccount): + if len(data) != 20: + raise ValueError(f"Invalid length: {len(data) + 1}") + else: + raise ValueError(f"Invalid address type: {typ}") + + return cls(typ, data) + + def bytes(self): + return bytes(self.data) + + def string(self): + if self.data == bytes([0]): + return TreasuryAddressString + + return utils.encode_from_base256_with_type(AddressHRP, self.data[0], self.data[1:]) + + def address_type(self): + return AddressType(self.data[0]) + + def is_treasury_address(self): + return self.address_type() == AddressType.Treasury + + def is_account_address(self): + t = self.address_type() + return t in (AddressType.Treasury, AddressType.BLSAccount) + + def is_validator_address(self): + return self.address_type() == AddressType.Validator diff --git a/python/bech32m.py b/python/bech32m.py new file mode 100644 index 0000000..5efb63e --- /dev/null +++ b/python/bech32m.py @@ -0,0 +1,137 @@ +# Copyright (c) 2017, 2020 Pieter Wuille +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +"""Reference implementation for Bech32/Bech32m and segwit addresses.""" + + +from enum import Enum + +class Encoding(Enum): + """Enumeration type to list the various supported encodings.""" + BECH32 = 1 + BECH32M = 2 + +CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" +BECH32M_CONST = 0x2bc830a3 + +def bech32_polymod(values): + """Internal function that computes the Bech32 checksum.""" + generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] + chk = 1 + for value in values: + top = chk >> 25 + chk = (chk & 0x1ffffff) << 5 ^ value + for i in range(5): + chk ^= generator[i] if ((top >> i) & 1) else 0 + return chk + + +def bech32_hrp_expand(hrp): + """Expand the HRP into values for checksum computation.""" + return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp] + + +def bech32_verify_checksum(hrp, data): + """Verify a checksum given HRP and converted data characters.""" + const = bech32_polymod(bech32_hrp_expand(hrp) + data) + if const == 1: + return Encoding.BECH32 + if const == BECH32M_CONST: + return Encoding.BECH32M + return None + +def bech32_create_checksum(hrp, data, spec): + """Compute the checksum values given HRP and data.""" + values = bech32_hrp_expand(hrp) + data + const = BECH32M_CONST if spec == Encoding.BECH32M else 1 + polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const + return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)] + + +def bech32_encode(hrp, data, spec): + """Compute a Bech32 string given HRP and data values.""" + combined = data + bech32_create_checksum(hrp, data, spec) + return hrp + '1' + ''.join([CHARSET[d] for d in combined]) + +def bech32_decode(bech): + """Validate a Bech32/Bech32m string, and determine HRP and data.""" + if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or + (bech.lower() != bech and bech.upper() != bech)): + return (None, None, None) + bech = bech.lower() + pos = bech.rfind('1') + if pos < 1 or pos + 7 > len(bech): + return (None, None, None) + if not all(x in CHARSET for x in bech[pos+1:]): + return (None, None, None) + hrp = bech[:pos] + data = [CHARSET.find(x) for x in bech[pos+1:]] + spec = bech32_verify_checksum(hrp, data) + if spec is None: + return (None, None, None) + return (hrp, data[:-6], spec) + +def convertbits(data, frombits, tobits, pad=True): + """General power-of-2 base conversion.""" + acc = 0 + bits = 0 + ret = [] + maxv = (1 << tobits) - 1 + max_acc = (1 << (frombits + tobits - 1)) - 1 + for value in data: + if value < 0 or (value >> frombits): + return None + acc = ((acc << frombits) | value) & max_acc + bits += frombits + while bits >= tobits: + bits -= tobits + ret.append((acc >> bits) & maxv) + if pad: + if bits: + ret.append((acc << (tobits - bits)) & maxv) + elif bits >= frombits or ((acc << (tobits - bits)) & maxv): + return None + return ret + + +def decode(hrp, addr): + """Decode a segwit address.""" + hrpgot, data, spec = bech32_decode(addr) + if hrpgot != hrp: + return (None, None) + decoded = convertbits(data[1:], 5, 8, False) + if decoded is None or len(decoded) < 2 or len(decoded) > 40: + return (None, None) + if data[0] > 16: + return (None, None) + if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32: + return (None, None) + if data[0] == 0 and spec != Encoding.BECH32 or data[0] != 0 and spec != Encoding.BECH32M: + return (None, None) + return (data[0], decoded) + + +def encode(hrp, witver, witprog): + """Encode a segwit address.""" + spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M + ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec) + if decode(hrp, ret) == (None, None): + return None + return ret \ No newline at end of file diff --git a/python/main.py b/python/main.py new file mode 100644 index 0000000..dcc3bfc --- /dev/null +++ b/python/main.py @@ -0,0 +1,61 @@ +import grpc +import sys +import json +# Why can't?? +# from pactus import network_pb2 +# from pactus import network_pb2_grpc + +import public_key +import network_pb2 +import network_pb2_grpc + + +def load_json_file(file_path): + try: + with open(file_path, 'r') as file: + data = json.load(file) + return data + except FileNotFoundError: + print(f"File not found: {file_path}") + return None + except json.JSONDecodeError as e: + print(f"Error decoding JSON: {e}") + return None + + +def update_validator_map(url, valMap): + channel = grpc.insecure_channel(url) + stub = network_pb2_grpc.NetworkStub(channel) + req = network_pb2.GetNetworkInfoRequest() + info = stub.GetNetworkInfo(req) + + for peer in info.peers: + for i, key in enumerate(peer.consensus_keys): + pub = public_key.PublicKey.from_string(key) + valAddr = pub.validator_address().string() + valMap[valAddr] = i + +if __name__ == '__main__': + if len(sys.argv) != 2: + print("Usage: python main.py ") + else: + file_path = sys.argv[1] + json_data = load_json_file(file_path) + + valMap = {} + update_validator_map('172.104.46.145:50052', valMap) + update_validator_map('94.101.184.118:50052', valMap) + update_validator_map('51.158.118.181:50052', valMap) + update_validator_map('172.232.108.191:50052', valMap) + + for key, value in json_data.items(): + userValAddr = value['validator_address'] + index = valMap.get(userValAddr, None) + if index is not None: + if index != 0: + print("user {} staked in wrong validator. index: {}".format( + value['discord_name'], index)) + else: + print("unable to find validator {} information for user {}".format( + value['validator_address'], + value['discord_name'])) diff --git a/python/network_pb2.py b/python/network_pb2.py new file mode 100644 index 0000000..f582ac6 --- /dev/null +++ b/python/network_pb2.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: network.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\rnetwork.proto\x12\x06pactus\"\x17\n\x15GetNetworkInfoRequest\"\xe3\x03\n\x16GetNetworkInfoResponse\x12(\n\x10total_sent_bytes\x18\x01 \x01(\x05R\x0etotalSentBytes\x12\x30\n\x14total_received_bytes\x18\x02 \x01(\x05R\x12totalReceivedBytes\x12\x1d\n\nstarted_at\x18\x03 \x01(\x03R\tstartedAt\x12&\n\x05peers\x18\x04 \x03(\x0b\x32\x10.pactus.PeerInfoR\x05peers\x12L\n\nsent_bytes\x18\x05 \x03(\x0b\x32-.pactus.GetNetworkInfoResponse.SentBytesEntryR\tsentBytes\x12X\n\x0ereceived_bytes\x18\x06 \x03(\x0b\x32\x31.pactus.GetNetworkInfoResponse.ReceivedBytesEntryR\rreceivedBytes\x1a<\n\x0eSentBytesEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x03R\x05value:\x02\x38\x01\x1a@\n\x12ReceivedBytesEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x03R\x05value:\x02\x38\x01\"\x14\n\x12GetNodeInfoRequest\"\x98\x01\n\x13GetNodeInfoResponse\x12\x18\n\x07moniker\x18\x01 \x01(\tR\x07moniker\x12\x14\n\x05\x61gent\x18\x02 \x01(\tR\x05\x61gent\x12\x17\n\x07peer_id\x18\x03 \x01(\x0cR\x06peerId\x12\"\n\x0creachability\x18\x04 \x01(\tR\x0creachability\x12\x14\n\x05\x61\x64\x64rs\x18\x05 \x03(\tR\x05\x61\x64\x64rs\"\xc0\x06\n\x08PeerInfo\x12\x16\n\x06status\x18\x01 \x01(\x05R\x06status\x12\x18\n\x07moniker\x18\x02 \x01(\tR\x07moniker\x12\x14\n\x05\x61gent\x18\x03 \x01(\tR\x05\x61gent\x12\x17\n\x07peer_id\x18\x04 \x01(\x0cR\x06peerId\x12%\n\x0e\x63onsensus_keys\x18\x05 \x03(\tR\rconsensusKeys\x12\x1a\n\x08services\x18\x06 \x01(\rR\x08services\x12&\n\x0flast_block_hash\x18\x07 \x01(\x0cR\rlastBlockHash\x12\x16\n\x06height\x18\x08 \x01(\rR\x06height\x12+\n\x11received_messages\x18\t \x01(\x05R\x10receivedMessages\x12)\n\x10invalid_messages\x18\n \x01(\x05R\x0finvalidMessages\x12\x1b\n\tlast_sent\x18\x0b \x01(\x03R\x08lastSent\x12#\n\rlast_received\x18\x0c \x01(\x03R\x0clastReceived\x12>\n\nsent_bytes\x18\r \x03(\x0b\x32\x1f.pactus.PeerInfo.SentBytesEntryR\tsentBytes\x12J\n\x0ereceived_bytes\x18\x0e \x03(\x0b\x32#.pactus.PeerInfo.ReceivedBytesEntryR\rreceivedBytes\x12\x18\n\x07\x61\x64\x64ress\x18\x0f \x01(\tR\x07\x61\x64\x64ress\x12\x1c\n\tdirection\x18\x10 \x01(\tR\tdirection\x12\x1c\n\tprotocols\x18\x11 \x03(\tR\tprotocols\x12%\n\x0etotal_sessions\x18\x12 \x01(\x05R\rtotalSessions\x12-\n\x12\x63ompleted_sessions\x18\x13 \x01(\x05R\x11\x63ompletedSessions\x1a<\n\x0eSentBytesEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x03R\x05value:\x02\x38\x01\x1a@\n\x12ReceivedBytesEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x03R\x05value:\x02\x38\x01\x32\xa2\x01\n\x07Network\x12O\n\x0eGetNetworkInfo\x12\x1d.pactus.GetNetworkInfoRequest\x1a\x1e.pactus.GetNetworkInfoResponse\x12\x46\n\x0bGetNodeInfo\x12\x1a.pactus.GetNodeInfoRequest\x1a\x1b.pactus.GetNodeInfoResponseBB\n\x0epactus.networkZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'network_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\016pactus.networkZ0github.com/pactus-project/pactus/www/grpc/pactus' + _GETNETWORKINFORESPONSE_SENTBYTESENTRY._options = None + _GETNETWORKINFORESPONSE_SENTBYTESENTRY._serialized_options = b'8\001' + _GETNETWORKINFORESPONSE_RECEIVEDBYTESENTRY._options = None + _GETNETWORKINFORESPONSE_RECEIVEDBYTESENTRY._serialized_options = b'8\001' + _PEERINFO_SENTBYTESENTRY._options = None + _PEERINFO_SENTBYTESENTRY._serialized_options = b'8\001' + _PEERINFO_RECEIVEDBYTESENTRY._options = None + _PEERINFO_RECEIVEDBYTESENTRY._serialized_options = b'8\001' + _GETNETWORKINFOREQUEST._serialized_start=25 + _GETNETWORKINFOREQUEST._serialized_end=48 + _GETNETWORKINFORESPONSE._serialized_start=51 + _GETNETWORKINFORESPONSE._serialized_end=534 + _GETNETWORKINFORESPONSE_SENTBYTESENTRY._serialized_start=408 + _GETNETWORKINFORESPONSE_SENTBYTESENTRY._serialized_end=468 + _GETNETWORKINFORESPONSE_RECEIVEDBYTESENTRY._serialized_start=470 + _GETNETWORKINFORESPONSE_RECEIVEDBYTESENTRY._serialized_end=534 + _GETNODEINFOREQUEST._serialized_start=536 + _GETNODEINFOREQUEST._serialized_end=556 + _GETNODEINFORESPONSE._serialized_start=559 + _GETNODEINFORESPONSE._serialized_end=711 + _PEERINFO._serialized_start=714 + _PEERINFO._serialized_end=1546 + _PEERINFO_SENTBYTESENTRY._serialized_start=408 + _PEERINFO_SENTBYTESENTRY._serialized_end=468 + _PEERINFO_RECEIVEDBYTESENTRY._serialized_start=470 + _PEERINFO_RECEIVEDBYTESENTRY._serialized_end=534 + _NETWORK._serialized_start=1549 + _NETWORK._serialized_end=1711 +# @@protoc_insertion_point(module_scope) diff --git a/python/network_pb2_grpc.py b/python/network_pb2_grpc.py new file mode 100644 index 0000000..8c1ac8c --- /dev/null +++ b/python/network_pb2_grpc.py @@ -0,0 +1,99 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +import network_pb2 as network__pb2 + + +class NetworkStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.GetNetworkInfo = channel.unary_unary( + '/pactus.Network/GetNetworkInfo', + request_serializer=network__pb2.GetNetworkInfoRequest.SerializeToString, + response_deserializer=network__pb2.GetNetworkInfoResponse.FromString, + ) + self.GetNodeInfo = channel.unary_unary( + '/pactus.Network/GetNodeInfo', + request_serializer=network__pb2.GetNodeInfoRequest.SerializeToString, + response_deserializer=network__pb2.GetNodeInfoResponse.FromString, + ) + + +class NetworkServicer(object): + """Missing associated documentation comment in .proto file.""" + + def GetNetworkInfo(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetNodeInfo(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_NetworkServicer_to_server(servicer, server): + rpc_method_handlers = { + 'GetNetworkInfo': grpc.unary_unary_rpc_method_handler( + servicer.GetNetworkInfo, + request_deserializer=network__pb2.GetNetworkInfoRequest.FromString, + response_serializer=network__pb2.GetNetworkInfoResponse.SerializeToString, + ), + 'GetNodeInfo': grpc.unary_unary_rpc_method_handler( + servicer.GetNodeInfo, + request_deserializer=network__pb2.GetNodeInfoRequest.FromString, + response_serializer=network__pb2.GetNodeInfoResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'pactus.Network', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class Network(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def GetNetworkInfo(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Network/GetNetworkInfo', + network__pb2.GetNetworkInfoRequest.SerializeToString, + network__pb2.GetNetworkInfoResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetNodeInfo(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Network/GetNodeInfo', + network__pb2.GetNodeInfoRequest.SerializeToString, + network__pb2.GetNodeInfoResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/python/pactus/blockchain_pb2.py b/python/pactus/blockchain_pb2.py new file mode 100644 index 0000000..8c4d2c0 --- /dev/null +++ b/python/pactus/blockchain_pb2.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: blockchain.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +import transaction_pb2 as transaction__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10\x62lockchain.proto\x12\x06pactus\x1a\x11transaction.proto\"-\n\x11GetAccountRequest\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\"C\n\x12GetAccountResponse\x12-\n\x07\x61\x63\x63ount\x18\x01 \x01(\x0b\x32\x13.pactus.AccountInfoR\x07\x61\x63\x63ount\"\x1e\n\x1cGetValidatorAddressesRequest\"=\n\x1dGetValidatorAddressesResponse\x12\x1c\n\taddresses\x18\x01 \x03(\tR\taddresses\"/\n\x13GetValidatorRequest\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\"5\n\x1bGetValidatorByNumberRequest\x12\x16\n\x06number\x18\x01 \x01(\x05R\x06number\"K\n\x14GetValidatorResponse\x12\x33\n\tvalidator\x18\x01 \x01(\x0b\x32\x15.pactus.ValidatorInfoR\tvalidator\"/\n\x13GetPublicKeyRequest\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\"5\n\x14GetPublicKeyResponse\x12\x1d\n\npublic_key\x18\x01 \x01(\tR\tpublicKey\"_\n\x0fGetBlockRequest\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\x12\x34\n\tverbosity\x18\x02 \x01(\x0e\x32\x16.pactus.BlockVerbosityR\tverbosity\"\x83\x02\n\x10GetBlockResponse\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\x12\x12\n\x04hash\x18\x02 \x01(\x0cR\x04hash\x12\x12\n\x04\x64\x61ta\x18\x03 \x01(\x0cR\x04\x64\x61ta\x12\x1d\n\nblock_time\x18\x04 \x01(\rR\tblockTime\x12/\n\x06header\x18\x05 \x01(\x0b\x32\x17.pactus.BlockHeaderInfoR\x06header\x12\x34\n\tprev_cert\x18\x06 \x01(\x0b\x32\x17.pactus.CertificateInfoR\x08prevCert\x12)\n\x03txs\x18\x07 \x03(\x0b\x32\x17.pactus.TransactionInfoR\x03txs\"-\n\x13GetBlockHashRequest\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\"*\n\x14GetBlockHashResponse\x12\x12\n\x04hash\x18\x01 \x01(\x0cR\x04hash\"+\n\x15GetBlockHeightRequest\x12\x12\n\x04hash\x18\x01 \x01(\x0cR\x04hash\"0\n\x16GetBlockHeightResponse\x12\x16\n\x06height\x18\x01 \x01(\rR\x06height\"\x1a\n\x18GetBlockchainInfoRequest\"\xd5\x02\n\x19GetBlockchainInfoResponse\x12*\n\x11last_block_height\x18\x01 \x01(\rR\x0flastBlockHeight\x12&\n\x0flast_block_hash\x18\x02 \x01(\x0cR\rlastBlockHash\x12%\n\x0etotal_accounts\x18\x03 \x01(\x05R\rtotalAccounts\x12)\n\x10total_validators\x18\x04 \x01(\x05R\x0ftotalValidators\x12\x1f\n\x0btotal_power\x18\x05 \x01(\x03R\ntotalPower\x12\'\n\x0f\x63ommittee_power\x18\x06 \x01(\x03R\x0e\x63ommitteePower\x12H\n\x14\x63ommittee_validators\x18\x07 \x03(\x0b\x32\x15.pactus.ValidatorInfoR\x13\x63ommitteeValidators\"\x19\n\x17GetConsensusInfoRequest\"O\n\x18GetConsensusInfoResponse\x12\x33\n\tinstances\x18\x01 \x03(\x0b\x32\x15.pactus.ConsensusInfoR\tinstances\"\xad\x02\n\rValidatorInfo\x12\x12\n\x04hash\x18\x01 \x01(\x0cR\x04hash\x12\x12\n\x04\x64\x61ta\x18\x02 \x01(\x0cR\x04\x64\x61ta\x12\x1d\n\npublic_key\x18\x03 \x01(\tR\tpublicKey\x12\x16\n\x06number\x18\x04 \x01(\x05R\x06number\x12\x14\n\x05stake\x18\x05 \x01(\x03R\x05stake\x12.\n\x13last_bonding_height\x18\x06 \x01(\rR\x11lastBondingHeight\x12\x32\n\x15last_sortition_height\x18\x07 \x01(\rR\x13lastSortitionHeight\x12)\n\x10unbonding_height\x18\x08 \x01(\rR\x0funbondingHeight\x12\x18\n\x07\x61\x64\x64ress\x18\t \x01(\tR\x07\x61\x64\x64ress\"\x81\x01\n\x0b\x41\x63\x63ountInfo\x12\x12\n\x04hash\x18\x01 \x01(\x0cR\x04hash\x12\x12\n\x04\x64\x61ta\x18\x02 \x01(\x0cR\x04\x64\x61ta\x12\x16\n\x06number\x18\x03 \x01(\x05R\x06number\x12\x18\n\x07\x62\x61lance\x18\x04 \x01(\x03R\x07\x62\x61lance\x12\x18\n\x07\x61\x64\x64ress\x18\x05 \x01(\tR\x07\x61\x64\x64ress\"\xc4\x01\n\x0f\x42lockHeaderInfo\x12\x18\n\x07version\x18\x01 \x01(\x05R\x07version\x12&\n\x0fprev_block_hash\x18\x02 \x01(\x0cR\rprevBlockHash\x12\x1d\n\nstate_root\x18\x03 \x01(\x0cR\tstateRoot\x12%\n\x0esortition_seed\x18\x04 \x01(\x0cR\rsortitionSeed\x12)\n\x10proposer_address\x18\x05 \x01(\tR\x0fproposerAddress\"\x97\x01\n\x0f\x43\x65rtificateInfo\x12\x12\n\x04hash\x18\x01 \x01(\x0cR\x04hash\x12\x14\n\x05round\x18\x02 \x01(\x05R\x05round\x12\x1e\n\ncommitters\x18\x03 \x03(\x05R\ncommitters\x12\x1c\n\tabsentees\x18\x04 \x03(\x05R\tabsentees\x12\x1c\n\tsignature\x18\x05 \x01(\x0cR\tsignature\"{\n\x08VoteInfo\x12$\n\x04type\x18\x01 \x01(\x0e\x32\x10.pactus.VoteTypeR\x04type\x12\x14\n\x05voter\x18\x02 \x01(\tR\x05voter\x12\x1d\n\nblock_hash\x18\x03 \x01(\x0cR\tblockHash\x12\x14\n\x05round\x18\x04 \x01(\x05R\x05round\"\x97\x01\n\rConsensusInfo\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\x12\x16\n\x06\x41\x63tive\x18\x02 \x01(\x08R\x06\x41\x63tive\x12\x16\n\x06height\x18\x03 \x01(\rR\x06height\x12\x14\n\x05round\x18\x04 \x01(\x05R\x05round\x12&\n\x05votes\x18\x05 \x03(\x0b\x32\x10.pactus.VoteInfoR\x05votes*H\n\x0e\x42lockVerbosity\x12\x0e\n\nBLOCK_DATA\x10\x00\x12\x0e\n\nBLOCK_INFO\x10\x01\x12\x16\n\x12\x42LOCK_TRANSACTIONS\x10\x02*\\\n\x08VoteType\x12\x10\n\x0cVOTE_UNKNOWN\x10\x00\x12\x10\n\x0cVOTE_PREPARE\x10\x01\x12\x12\n\x0eVOTE_PRECOMMIT\x10\x02\x12\x18\n\x14VOTE_CHANGE_PROPOSER\x10\x03\x32\xb4\x06\n\nBlockchain\x12=\n\x08GetBlock\x12\x17.pactus.GetBlockRequest\x1a\x18.pactus.GetBlockResponse\x12I\n\x0cGetBlockHash\x12\x1b.pactus.GetBlockHashRequest\x1a\x1c.pactus.GetBlockHashResponse\x12O\n\x0eGetBlockHeight\x12\x1d.pactus.GetBlockHeightRequest\x1a\x1e.pactus.GetBlockHeightResponse\x12X\n\x11GetBlockchainInfo\x12 .pactus.GetBlockchainInfoRequest\x1a!.pactus.GetBlockchainInfoResponse\x12U\n\x10GetConsensusInfo\x12\x1f.pactus.GetConsensusInfoRequest\x1a .pactus.GetConsensusInfoResponse\x12\x43\n\nGetAccount\x12\x19.pactus.GetAccountRequest\x1a\x1a.pactus.GetAccountResponse\x12I\n\x0cGetValidator\x12\x1b.pactus.GetValidatorRequest\x1a\x1c.pactus.GetValidatorResponse\x12Y\n\x14GetValidatorByNumber\x12#.pactus.GetValidatorByNumberRequest\x1a\x1c.pactus.GetValidatorResponse\x12\x64\n\x15GetValidatorAddresses\x12$.pactus.GetValidatorAddressesRequest\x1a%.pactus.GetValidatorAddressesResponse\x12I\n\x0cGetPublicKey\x12\x1b.pactus.GetPublicKeyRequest\x1a\x1c.pactus.GetPublicKeyResponseBE\n\x11pactus.blockchainZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'blockchain_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\021pactus.blockchainZ0github.com/pactus-project/pactus/www/grpc/pactus' + _BLOCKVERBOSITY._serialized_start=2636 + _BLOCKVERBOSITY._serialized_end=2708 + _VOTETYPE._serialized_start=2710 + _VOTETYPE._serialized_end=2802 + _GETACCOUNTREQUEST._serialized_start=47 + _GETACCOUNTREQUEST._serialized_end=92 + _GETACCOUNTRESPONSE._serialized_start=94 + _GETACCOUNTRESPONSE._serialized_end=161 + _GETVALIDATORADDRESSESREQUEST._serialized_start=163 + _GETVALIDATORADDRESSESREQUEST._serialized_end=193 + _GETVALIDATORADDRESSESRESPONSE._serialized_start=195 + _GETVALIDATORADDRESSESRESPONSE._serialized_end=256 + _GETVALIDATORREQUEST._serialized_start=258 + _GETVALIDATORREQUEST._serialized_end=305 + _GETVALIDATORBYNUMBERREQUEST._serialized_start=307 + _GETVALIDATORBYNUMBERREQUEST._serialized_end=360 + _GETVALIDATORRESPONSE._serialized_start=362 + _GETVALIDATORRESPONSE._serialized_end=437 + _GETPUBLICKEYREQUEST._serialized_start=439 + _GETPUBLICKEYREQUEST._serialized_end=486 + _GETPUBLICKEYRESPONSE._serialized_start=488 + _GETPUBLICKEYRESPONSE._serialized_end=541 + _GETBLOCKREQUEST._serialized_start=543 + _GETBLOCKREQUEST._serialized_end=638 + _GETBLOCKRESPONSE._serialized_start=641 + _GETBLOCKRESPONSE._serialized_end=900 + _GETBLOCKHASHREQUEST._serialized_start=902 + _GETBLOCKHASHREQUEST._serialized_end=947 + _GETBLOCKHASHRESPONSE._serialized_start=949 + _GETBLOCKHASHRESPONSE._serialized_end=991 + _GETBLOCKHEIGHTREQUEST._serialized_start=993 + _GETBLOCKHEIGHTREQUEST._serialized_end=1036 + _GETBLOCKHEIGHTRESPONSE._serialized_start=1038 + _GETBLOCKHEIGHTRESPONSE._serialized_end=1086 + _GETBLOCKCHAININFOREQUEST._serialized_start=1088 + _GETBLOCKCHAININFOREQUEST._serialized_end=1114 + _GETBLOCKCHAININFORESPONSE._serialized_start=1117 + _GETBLOCKCHAININFORESPONSE._serialized_end=1458 + _GETCONSENSUSINFOREQUEST._serialized_start=1460 + _GETCONSENSUSINFOREQUEST._serialized_end=1485 + _GETCONSENSUSINFORESPONSE._serialized_start=1487 + _GETCONSENSUSINFORESPONSE._serialized_end=1566 + _VALIDATORINFO._serialized_start=1569 + _VALIDATORINFO._serialized_end=1870 + _ACCOUNTINFO._serialized_start=1873 + _ACCOUNTINFO._serialized_end=2002 + _BLOCKHEADERINFO._serialized_start=2005 + _BLOCKHEADERINFO._serialized_end=2201 + _CERTIFICATEINFO._serialized_start=2204 + _CERTIFICATEINFO._serialized_end=2355 + _VOTEINFO._serialized_start=2357 + _VOTEINFO._serialized_end=2480 + _CONSENSUSINFO._serialized_start=2483 + _CONSENSUSINFO._serialized_end=2634 + _BLOCKCHAIN._serialized_start=2805 + _BLOCKCHAIN._serialized_end=3625 +# @@protoc_insertion_point(module_scope) diff --git a/python/pactus/blockchain_pb2_grpc.py b/python/pactus/blockchain_pb2_grpc.py new file mode 100644 index 0000000..16f0e3c --- /dev/null +++ b/python/pactus/blockchain_pb2_grpc.py @@ -0,0 +1,363 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +import blockchain_pb2 as blockchain__pb2 + + +class BlockchainStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.GetBlock = channel.unary_unary( + '/pactus.Blockchain/GetBlock', + request_serializer=blockchain__pb2.GetBlockRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetBlockResponse.FromString, + ) + self.GetBlockHash = channel.unary_unary( + '/pactus.Blockchain/GetBlockHash', + request_serializer=blockchain__pb2.GetBlockHashRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetBlockHashResponse.FromString, + ) + self.GetBlockHeight = channel.unary_unary( + '/pactus.Blockchain/GetBlockHeight', + request_serializer=blockchain__pb2.GetBlockHeightRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetBlockHeightResponse.FromString, + ) + self.GetBlockchainInfo = channel.unary_unary( + '/pactus.Blockchain/GetBlockchainInfo', + request_serializer=blockchain__pb2.GetBlockchainInfoRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetBlockchainInfoResponse.FromString, + ) + self.GetConsensusInfo = channel.unary_unary( + '/pactus.Blockchain/GetConsensusInfo', + request_serializer=blockchain__pb2.GetConsensusInfoRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetConsensusInfoResponse.FromString, + ) + self.GetAccount = channel.unary_unary( + '/pactus.Blockchain/GetAccount', + request_serializer=blockchain__pb2.GetAccountRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetAccountResponse.FromString, + ) + self.GetValidator = channel.unary_unary( + '/pactus.Blockchain/GetValidator', + request_serializer=blockchain__pb2.GetValidatorRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetValidatorResponse.FromString, + ) + self.GetValidatorByNumber = channel.unary_unary( + '/pactus.Blockchain/GetValidatorByNumber', + request_serializer=blockchain__pb2.GetValidatorByNumberRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetValidatorResponse.FromString, + ) + self.GetValidatorAddresses = channel.unary_unary( + '/pactus.Blockchain/GetValidatorAddresses', + request_serializer=blockchain__pb2.GetValidatorAddressesRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetValidatorAddressesResponse.FromString, + ) + self.GetPublicKey = channel.unary_unary( + '/pactus.Blockchain/GetPublicKey', + request_serializer=blockchain__pb2.GetPublicKeyRequest.SerializeToString, + response_deserializer=blockchain__pb2.GetPublicKeyResponse.FromString, + ) + + +class BlockchainServicer(object): + """Missing associated documentation comment in .proto file.""" + + def GetBlock(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetBlockHash(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetBlockHeight(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetBlockchainInfo(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetConsensusInfo(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetAccount(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetValidator(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetValidatorByNumber(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetValidatorAddresses(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetPublicKey(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_BlockchainServicer_to_server(servicer, server): + rpc_method_handlers = { + 'GetBlock': grpc.unary_unary_rpc_method_handler( + servicer.GetBlock, + request_deserializer=blockchain__pb2.GetBlockRequest.FromString, + response_serializer=blockchain__pb2.GetBlockResponse.SerializeToString, + ), + 'GetBlockHash': grpc.unary_unary_rpc_method_handler( + servicer.GetBlockHash, + request_deserializer=blockchain__pb2.GetBlockHashRequest.FromString, + response_serializer=blockchain__pb2.GetBlockHashResponse.SerializeToString, + ), + 'GetBlockHeight': grpc.unary_unary_rpc_method_handler( + servicer.GetBlockHeight, + request_deserializer=blockchain__pb2.GetBlockHeightRequest.FromString, + response_serializer=blockchain__pb2.GetBlockHeightResponse.SerializeToString, + ), + 'GetBlockchainInfo': grpc.unary_unary_rpc_method_handler( + servicer.GetBlockchainInfo, + request_deserializer=blockchain__pb2.GetBlockchainInfoRequest.FromString, + response_serializer=blockchain__pb2.GetBlockchainInfoResponse.SerializeToString, + ), + 'GetConsensusInfo': grpc.unary_unary_rpc_method_handler( + servicer.GetConsensusInfo, + request_deserializer=blockchain__pb2.GetConsensusInfoRequest.FromString, + response_serializer=blockchain__pb2.GetConsensusInfoResponse.SerializeToString, + ), + 'GetAccount': grpc.unary_unary_rpc_method_handler( + servicer.GetAccount, + request_deserializer=blockchain__pb2.GetAccountRequest.FromString, + response_serializer=blockchain__pb2.GetAccountResponse.SerializeToString, + ), + 'GetValidator': grpc.unary_unary_rpc_method_handler( + servicer.GetValidator, + request_deserializer=blockchain__pb2.GetValidatorRequest.FromString, + response_serializer=blockchain__pb2.GetValidatorResponse.SerializeToString, + ), + 'GetValidatorByNumber': grpc.unary_unary_rpc_method_handler( + servicer.GetValidatorByNumber, + request_deserializer=blockchain__pb2.GetValidatorByNumberRequest.FromString, + response_serializer=blockchain__pb2.GetValidatorResponse.SerializeToString, + ), + 'GetValidatorAddresses': grpc.unary_unary_rpc_method_handler( + servicer.GetValidatorAddresses, + request_deserializer=blockchain__pb2.GetValidatorAddressesRequest.FromString, + response_serializer=blockchain__pb2.GetValidatorAddressesResponse.SerializeToString, + ), + 'GetPublicKey': grpc.unary_unary_rpc_method_handler( + servicer.GetPublicKey, + request_deserializer=blockchain__pb2.GetPublicKeyRequest.FromString, + response_serializer=blockchain__pb2.GetPublicKeyResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'pactus.Blockchain', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class Blockchain(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def GetBlock(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetBlock', + blockchain__pb2.GetBlockRequest.SerializeToString, + blockchain__pb2.GetBlockResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetBlockHash(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetBlockHash', + blockchain__pb2.GetBlockHashRequest.SerializeToString, + blockchain__pb2.GetBlockHashResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetBlockHeight(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetBlockHeight', + blockchain__pb2.GetBlockHeightRequest.SerializeToString, + blockchain__pb2.GetBlockHeightResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetBlockchainInfo(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetBlockchainInfo', + blockchain__pb2.GetBlockchainInfoRequest.SerializeToString, + blockchain__pb2.GetBlockchainInfoResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetConsensusInfo(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetConsensusInfo', + blockchain__pb2.GetConsensusInfoRequest.SerializeToString, + blockchain__pb2.GetConsensusInfoResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetAccount(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetAccount', + blockchain__pb2.GetAccountRequest.SerializeToString, + blockchain__pb2.GetAccountResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetValidator(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetValidator', + blockchain__pb2.GetValidatorRequest.SerializeToString, + blockchain__pb2.GetValidatorResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetValidatorByNumber(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetValidatorByNumber', + blockchain__pb2.GetValidatorByNumberRequest.SerializeToString, + blockchain__pb2.GetValidatorResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetValidatorAddresses(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetValidatorAddresses', + blockchain__pb2.GetValidatorAddressesRequest.SerializeToString, + blockchain__pb2.GetValidatorAddressesResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetPublicKey(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Blockchain/GetPublicKey', + blockchain__pb2.GetPublicKeyRequest.SerializeToString, + blockchain__pb2.GetPublicKeyResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/python/pactus/network_pb2.py b/python/pactus/network_pb2.py new file mode 100644 index 0000000..f582ac6 --- /dev/null +++ b/python/pactus/network_pb2.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: network.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\rnetwork.proto\x12\x06pactus\"\x17\n\x15GetNetworkInfoRequest\"\xe3\x03\n\x16GetNetworkInfoResponse\x12(\n\x10total_sent_bytes\x18\x01 \x01(\x05R\x0etotalSentBytes\x12\x30\n\x14total_received_bytes\x18\x02 \x01(\x05R\x12totalReceivedBytes\x12\x1d\n\nstarted_at\x18\x03 \x01(\x03R\tstartedAt\x12&\n\x05peers\x18\x04 \x03(\x0b\x32\x10.pactus.PeerInfoR\x05peers\x12L\n\nsent_bytes\x18\x05 \x03(\x0b\x32-.pactus.GetNetworkInfoResponse.SentBytesEntryR\tsentBytes\x12X\n\x0ereceived_bytes\x18\x06 \x03(\x0b\x32\x31.pactus.GetNetworkInfoResponse.ReceivedBytesEntryR\rreceivedBytes\x1a<\n\x0eSentBytesEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x03R\x05value:\x02\x38\x01\x1a@\n\x12ReceivedBytesEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x03R\x05value:\x02\x38\x01\"\x14\n\x12GetNodeInfoRequest\"\x98\x01\n\x13GetNodeInfoResponse\x12\x18\n\x07moniker\x18\x01 \x01(\tR\x07moniker\x12\x14\n\x05\x61gent\x18\x02 \x01(\tR\x05\x61gent\x12\x17\n\x07peer_id\x18\x03 \x01(\x0cR\x06peerId\x12\"\n\x0creachability\x18\x04 \x01(\tR\x0creachability\x12\x14\n\x05\x61\x64\x64rs\x18\x05 \x03(\tR\x05\x61\x64\x64rs\"\xc0\x06\n\x08PeerInfo\x12\x16\n\x06status\x18\x01 \x01(\x05R\x06status\x12\x18\n\x07moniker\x18\x02 \x01(\tR\x07moniker\x12\x14\n\x05\x61gent\x18\x03 \x01(\tR\x05\x61gent\x12\x17\n\x07peer_id\x18\x04 \x01(\x0cR\x06peerId\x12%\n\x0e\x63onsensus_keys\x18\x05 \x03(\tR\rconsensusKeys\x12\x1a\n\x08services\x18\x06 \x01(\rR\x08services\x12&\n\x0flast_block_hash\x18\x07 \x01(\x0cR\rlastBlockHash\x12\x16\n\x06height\x18\x08 \x01(\rR\x06height\x12+\n\x11received_messages\x18\t \x01(\x05R\x10receivedMessages\x12)\n\x10invalid_messages\x18\n \x01(\x05R\x0finvalidMessages\x12\x1b\n\tlast_sent\x18\x0b \x01(\x03R\x08lastSent\x12#\n\rlast_received\x18\x0c \x01(\x03R\x0clastReceived\x12>\n\nsent_bytes\x18\r \x03(\x0b\x32\x1f.pactus.PeerInfo.SentBytesEntryR\tsentBytes\x12J\n\x0ereceived_bytes\x18\x0e \x03(\x0b\x32#.pactus.PeerInfo.ReceivedBytesEntryR\rreceivedBytes\x12\x18\n\x07\x61\x64\x64ress\x18\x0f \x01(\tR\x07\x61\x64\x64ress\x12\x1c\n\tdirection\x18\x10 \x01(\tR\tdirection\x12\x1c\n\tprotocols\x18\x11 \x03(\tR\tprotocols\x12%\n\x0etotal_sessions\x18\x12 \x01(\x05R\rtotalSessions\x12-\n\x12\x63ompleted_sessions\x18\x13 \x01(\x05R\x11\x63ompletedSessions\x1a<\n\x0eSentBytesEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x03R\x05value:\x02\x38\x01\x1a@\n\x12ReceivedBytesEntry\x12\x10\n\x03key\x18\x01 \x01(\x05R\x03key\x12\x14\n\x05value\x18\x02 \x01(\x03R\x05value:\x02\x38\x01\x32\xa2\x01\n\x07Network\x12O\n\x0eGetNetworkInfo\x12\x1d.pactus.GetNetworkInfoRequest\x1a\x1e.pactus.GetNetworkInfoResponse\x12\x46\n\x0bGetNodeInfo\x12\x1a.pactus.GetNodeInfoRequest\x1a\x1b.pactus.GetNodeInfoResponseBB\n\x0epactus.networkZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'network_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\016pactus.networkZ0github.com/pactus-project/pactus/www/grpc/pactus' + _GETNETWORKINFORESPONSE_SENTBYTESENTRY._options = None + _GETNETWORKINFORESPONSE_SENTBYTESENTRY._serialized_options = b'8\001' + _GETNETWORKINFORESPONSE_RECEIVEDBYTESENTRY._options = None + _GETNETWORKINFORESPONSE_RECEIVEDBYTESENTRY._serialized_options = b'8\001' + _PEERINFO_SENTBYTESENTRY._options = None + _PEERINFO_SENTBYTESENTRY._serialized_options = b'8\001' + _PEERINFO_RECEIVEDBYTESENTRY._options = None + _PEERINFO_RECEIVEDBYTESENTRY._serialized_options = b'8\001' + _GETNETWORKINFOREQUEST._serialized_start=25 + _GETNETWORKINFOREQUEST._serialized_end=48 + _GETNETWORKINFORESPONSE._serialized_start=51 + _GETNETWORKINFORESPONSE._serialized_end=534 + _GETNETWORKINFORESPONSE_SENTBYTESENTRY._serialized_start=408 + _GETNETWORKINFORESPONSE_SENTBYTESENTRY._serialized_end=468 + _GETNETWORKINFORESPONSE_RECEIVEDBYTESENTRY._serialized_start=470 + _GETNETWORKINFORESPONSE_RECEIVEDBYTESENTRY._serialized_end=534 + _GETNODEINFOREQUEST._serialized_start=536 + _GETNODEINFOREQUEST._serialized_end=556 + _GETNODEINFORESPONSE._serialized_start=559 + _GETNODEINFORESPONSE._serialized_end=711 + _PEERINFO._serialized_start=714 + _PEERINFO._serialized_end=1546 + _PEERINFO_SENTBYTESENTRY._serialized_start=408 + _PEERINFO_SENTBYTESENTRY._serialized_end=468 + _PEERINFO_RECEIVEDBYTESENTRY._serialized_start=470 + _PEERINFO_RECEIVEDBYTESENTRY._serialized_end=534 + _NETWORK._serialized_start=1549 + _NETWORK._serialized_end=1711 +# @@protoc_insertion_point(module_scope) diff --git a/python/pactus/network_pb2_grpc.py b/python/pactus/network_pb2_grpc.py new file mode 100644 index 0000000..8c1ac8c --- /dev/null +++ b/python/pactus/network_pb2_grpc.py @@ -0,0 +1,99 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +import network_pb2 as network__pb2 + + +class NetworkStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.GetNetworkInfo = channel.unary_unary( + '/pactus.Network/GetNetworkInfo', + request_serializer=network__pb2.GetNetworkInfoRequest.SerializeToString, + response_deserializer=network__pb2.GetNetworkInfoResponse.FromString, + ) + self.GetNodeInfo = channel.unary_unary( + '/pactus.Network/GetNodeInfo', + request_serializer=network__pb2.GetNodeInfoRequest.SerializeToString, + response_deserializer=network__pb2.GetNodeInfoResponse.FromString, + ) + + +class NetworkServicer(object): + """Missing associated documentation comment in .proto file.""" + + def GetNetworkInfo(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetNodeInfo(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_NetworkServicer_to_server(servicer, server): + rpc_method_handlers = { + 'GetNetworkInfo': grpc.unary_unary_rpc_method_handler( + servicer.GetNetworkInfo, + request_deserializer=network__pb2.GetNetworkInfoRequest.FromString, + response_serializer=network__pb2.GetNetworkInfoResponse.SerializeToString, + ), + 'GetNodeInfo': grpc.unary_unary_rpc_method_handler( + servicer.GetNodeInfo, + request_deserializer=network__pb2.GetNodeInfoRequest.FromString, + response_serializer=network__pb2.GetNodeInfoResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'pactus.Network', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class Network(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def GetNetworkInfo(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Network/GetNetworkInfo', + network__pb2.GetNetworkInfoRequest.SerializeToString, + network__pb2.GetNetworkInfoResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetNodeInfo(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Network/GetNodeInfo', + network__pb2.GetNodeInfoRequest.SerializeToString, + network__pb2.GetNodeInfoResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/python/pactus/transaction_pb2.py b/python/pactus/transaction_pb2.py new file mode 100644 index 0000000..7e45136 --- /dev/null +++ b/python/pactus/transaction_pb2.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: transaction.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x11transaction.proto\x12\x06pactus\"c\n\x15GetTransactionRequest\x12\x0e\n\x02id\x18\x01 \x01(\x0cR\x02id\x12:\n\tverbosity\x18\x02 \x01(\x0e\x32\x1c.pactus.TransactionVerbosityR\tverbosity\"\x95\x01\n\x16GetTransactionResponse\x12!\n\x0c\x62lock_height\x18\x0c \x01(\rR\x0b\x62lockHeight\x12\x1d\n\nblock_time\x18\r \x01(\rR\tblockTime\x12\x39\n\x0btransaction\x18\x03 \x01(\x0b\x32\x17.pactus.TransactionInfoR\x0btransaction\"d\n\x13\x43\x61lculateFeeRequest\x12\x16\n\x06\x61mount\x18\x01 \x01(\x03R\x06\x61mount\x12\x35\n\x0bpayloadType\x18\x02 \x01(\x0e\x32\x13.pactus.PayloadTypeR\x0bpayloadType\"(\n\x14\x43\x61lculateFeeResponse\x12\x10\n\x03\x66\x65\x65\x18\x01 \x01(\x03R\x03\x66\x65\x65\"/\n\x19SendRawTransactionRequest\x12\x12\n\x04\x64\x61ta\x18\x01 \x01(\x0cR\x04\x64\x61ta\",\n\x1aSendRawTransactionResponse\x12\x0e\n\x02id\x18\x02 \x01(\x0cR\x02id\"\xb1\x01\n GetRawTransferTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12\x16\n\x06sender\x18\x02 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x03 \x01(\tR\x08receiver\x12\x16\n\x06\x61mount\x18\x04 \x01(\x03R\x06\x61mount\x12\x10\n\x03\x66\x65\x65\x18\x05 \x01(\x03R\x03\x66\x65\x65\x12\x12\n\x04memo\x18\x06 \x01(\tR\x04memo\"\xca\x01\n\x1cGetRawBondTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12\x16\n\x06sender\x18\x02 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x03 \x01(\tR\x08receiver\x12\x14\n\x05stake\x18\x04 \x01(\x03R\x05stake\x12\x1d\n\npublic_key\x18\x05 \x01(\tR\tpublicKey\x12\x10\n\x03\x66\x65\x65\x18\x06 \x01(\x03R\x03\x66\x65\x65\x12\x12\n\x04memo\x18\x07 \x01(\tR\x04memo\"~\n\x1eGetRawUnBondTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12+\n\x11validator_address\x18\x03 \x01(\tR\x10validatorAddress\x12\x12\n\x04memo\x18\x04 \x01(\tR\x04memo\"\xd3\x01\n GetRawWithdrawTransactionRequest\x12\x1b\n\tlock_time\x18\x01 \x01(\rR\x08lockTime\x12+\n\x11validator_address\x18\x03 \x01(\tR\x10validatorAddress\x12\'\n\x0f\x61\x63\x63ount_address\x18\x04 \x01(\tR\x0e\x61\x63\x63ountAddress\x12\x10\n\x03\x66\x65\x65\x18\x05 \x01(\x03R\x03\x66\x65\x65\x12\x16\n\x06\x61mount\x18\x06 \x01(\x03R\x06\x61mount\x12\x12\n\x04memo\x18\x07 \x01(\tR\x04memo\"D\n\x19GetRawTransactionResponse\x12\'\n\x0fraw_transaction\x18\x01 \x01(\x0cR\x0erawTransaction\"]\n\x0fPayloadTransfer\x12\x16\n\x06sender\x18\x01 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x02 \x01(\tR\x08receiver\x12\x16\n\x06\x61mount\x18\x03 \x01(\x03R\x06\x61mount\"W\n\x0bPayloadBond\x12\x16\n\x06sender\x18\x01 \x01(\tR\x06sender\x12\x1a\n\x08receiver\x18\x02 \x01(\tR\x08receiver\x12\x14\n\x05stake\x18\x03 \x01(\x03R\x05stake\"B\n\x10PayloadSortition\x12\x18\n\x07\x61\x64\x64ress\x18\x01 \x01(\tR\x07\x61\x64\x64ress\x12\x14\n\x05proof\x18\x02 \x01(\x0cR\x05proof\"-\n\rPayloadUnbond\x12\x1c\n\tvalidator\x18\x01 \x01(\tR\tvalidator\"M\n\x0fPayloadWithdraw\x12\x12\n\x04\x66rom\x18\x01 \x01(\tR\x04\x66rom\x12\x0e\n\x02to\x18\x02 \x01(\tR\x02to\x12\x16\n\x06\x61mount\x18\x03 \x01(\x03R\x06\x61mount\"\xab\x04\n\x0fTransactionInfo\x12\x0e\n\x02id\x18\x01 \x01(\x0cR\x02id\x12\x12\n\x04\x64\x61ta\x18\x02 \x01(\x0cR\x04\x64\x61ta\x12\x18\n\x07version\x18\x03 \x01(\x05R\x07version\x12\x1b\n\tlock_time\x18\x04 \x01(\rR\x08lockTime\x12\x14\n\x05value\x18\x05 \x01(\x03R\x05value\x12\x10\n\x03\x66\x65\x65\x18\x06 \x01(\x03R\x03\x66\x65\x65\x12\x35\n\x0bpayloadType\x18\x07 \x01(\x0e\x32\x13.pactus.PayloadTypeR\x0bpayloadType\x12\x35\n\x08transfer\x18\x1e \x01(\x0b\x32\x17.pactus.PayloadTransferH\x00R\x08transfer\x12)\n\x04\x62ond\x18\x1f \x01(\x0b\x32\x13.pactus.PayloadBondH\x00R\x04\x62ond\x12\x38\n\tsortition\x18 \x01(\x0b\x32\x18.pactus.PayloadSortitionH\x00R\tsortition\x12/\n\x06unbond\x18! \x01(\x0b\x32\x15.pactus.PayloadUnbondH\x00R\x06unbond\x12\x35\n\x08withdraw\x18\" \x01(\x0b\x32\x17.pactus.PayloadWithdrawH\x00R\x08withdraw\x12\x12\n\x04memo\x18\x08 \x01(\tR\x04memo\x12\x1d\n\npublic_key\x18\t \x01(\tR\tpublicKey\x12\x1c\n\tsignature\x18\n \x01(\x0cR\tsignatureB\t\n\x07payload*\x83\x01\n\x0bPayloadType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x14\n\x10TRANSFER_PAYLOAD\x10\x01\x12\x10\n\x0c\x42OND_PAYLOAD\x10\x02\x12\x15\n\x11SORTITION_PAYLOAD\x10\x03\x12\x12\n\x0eUNBOND_PAYLOAD\x10\x04\x12\x14\n\x10WITHDRAW_PAYLOAD\x10\x05*B\n\x14TransactionVerbosity\x12\x14\n\x10TRANSACTION_DATA\x10\x00\x12\x14\n\x10TRANSACTION_INFO\x10\x01\x32\xa2\x05\n\x0bTransaction\x12O\n\x0eGetTransaction\x12\x1d.pactus.GetTransactionRequest\x1a\x1e.pactus.GetTransactionResponse\x12I\n\x0c\x43\x61lculateFee\x12\x1b.pactus.CalculateFeeRequest\x1a\x1c.pactus.CalculateFeeResponse\x12[\n\x12SendRawTransaction\x12!.pactus.SendRawTransactionRequest\x1a\".pactus.SendRawTransactionResponse\x12h\n\x19GetRawTransferTransaction\x12(.pactus.GetRawTransferTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12`\n\x15GetRawBondTransaction\x12$.pactus.GetRawBondTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12\x64\n\x17GetRawUnBondTransaction\x12&.pactus.GetRawUnBondTransactionRequest\x1a!.pactus.GetRawTransactionResponse\x12h\n\x19GetRawWithdrawTransaction\x12(.pactus.GetRawWithdrawTransactionRequest\x1a!.pactus.GetRawTransactionResponseBF\n\x12pactus.transactionZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'transaction_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\022pactus.transactionZ0github.com/pactus-project/pactus/www/grpc/pactus' + _PAYLOADTYPE._serialized_start=2255 + _PAYLOADTYPE._serialized_end=2386 + _TRANSACTIONVERBOSITY._serialized_start=2388 + _TRANSACTIONVERBOSITY._serialized_end=2454 + _GETTRANSACTIONREQUEST._serialized_start=29 + _GETTRANSACTIONREQUEST._serialized_end=128 + _GETTRANSACTIONRESPONSE._serialized_start=131 + _GETTRANSACTIONRESPONSE._serialized_end=280 + _CALCULATEFEEREQUEST._serialized_start=282 + _CALCULATEFEEREQUEST._serialized_end=382 + _CALCULATEFEERESPONSE._serialized_start=384 + _CALCULATEFEERESPONSE._serialized_end=424 + _SENDRAWTRANSACTIONREQUEST._serialized_start=426 + _SENDRAWTRANSACTIONREQUEST._serialized_end=473 + _SENDRAWTRANSACTIONRESPONSE._serialized_start=475 + _SENDRAWTRANSACTIONRESPONSE._serialized_end=519 + _GETRAWTRANSFERTRANSACTIONREQUEST._serialized_start=522 + _GETRAWTRANSFERTRANSACTIONREQUEST._serialized_end=699 + _GETRAWBONDTRANSACTIONREQUEST._serialized_start=702 + _GETRAWBONDTRANSACTIONREQUEST._serialized_end=904 + _GETRAWUNBONDTRANSACTIONREQUEST._serialized_start=906 + _GETRAWUNBONDTRANSACTIONREQUEST._serialized_end=1032 + _GETRAWWITHDRAWTRANSACTIONREQUEST._serialized_start=1035 + _GETRAWWITHDRAWTRANSACTIONREQUEST._serialized_end=1246 + _GETRAWTRANSACTIONRESPONSE._serialized_start=1248 + _GETRAWTRANSACTIONRESPONSE._serialized_end=1316 + _PAYLOADTRANSFER._serialized_start=1318 + _PAYLOADTRANSFER._serialized_end=1411 + _PAYLOADBOND._serialized_start=1413 + _PAYLOADBOND._serialized_end=1500 + _PAYLOADSORTITION._serialized_start=1502 + _PAYLOADSORTITION._serialized_end=1568 + _PAYLOADUNBOND._serialized_start=1570 + _PAYLOADUNBOND._serialized_end=1615 + _PAYLOADWITHDRAW._serialized_start=1617 + _PAYLOADWITHDRAW._serialized_end=1694 + _TRANSACTIONINFO._serialized_start=1697 + _TRANSACTIONINFO._serialized_end=2252 + _TRANSACTION._serialized_start=2457 + _TRANSACTION._serialized_end=3131 +# @@protoc_insertion_point(module_scope) diff --git a/python/pactus/transaction_pb2_grpc.py b/python/pactus/transaction_pb2_grpc.py new file mode 100644 index 0000000..7ba156e --- /dev/null +++ b/python/pactus/transaction_pb2_grpc.py @@ -0,0 +1,264 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +import transaction_pb2 as transaction__pb2 + + +class TransactionStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.GetTransaction = channel.unary_unary( + '/pactus.Transaction/GetTransaction', + request_serializer=transaction__pb2.GetTransactionRequest.SerializeToString, + response_deserializer=transaction__pb2.GetTransactionResponse.FromString, + ) + self.CalculateFee = channel.unary_unary( + '/pactus.Transaction/CalculateFee', + request_serializer=transaction__pb2.CalculateFeeRequest.SerializeToString, + response_deserializer=transaction__pb2.CalculateFeeResponse.FromString, + ) + self.SendRawTransaction = channel.unary_unary( + '/pactus.Transaction/SendRawTransaction', + request_serializer=transaction__pb2.SendRawTransactionRequest.SerializeToString, + response_deserializer=transaction__pb2.SendRawTransactionResponse.FromString, + ) + self.GetRawTransferTransaction = channel.unary_unary( + '/pactus.Transaction/GetRawTransferTransaction', + request_serializer=transaction__pb2.GetRawTransferTransactionRequest.SerializeToString, + response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, + ) + self.GetRawBondTransaction = channel.unary_unary( + '/pactus.Transaction/GetRawBondTransaction', + request_serializer=transaction__pb2.GetRawBondTransactionRequest.SerializeToString, + response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, + ) + self.GetRawUnBondTransaction = channel.unary_unary( + '/pactus.Transaction/GetRawUnBondTransaction', + request_serializer=transaction__pb2.GetRawUnBondTransactionRequest.SerializeToString, + response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, + ) + self.GetRawWithdrawTransaction = channel.unary_unary( + '/pactus.Transaction/GetRawWithdrawTransaction', + request_serializer=transaction__pb2.GetRawWithdrawTransactionRequest.SerializeToString, + response_deserializer=transaction__pb2.GetRawTransactionResponse.FromString, + ) + + +class TransactionServicer(object): + """Missing associated documentation comment in .proto file.""" + + def GetTransaction(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def CalculateFee(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def SendRawTransaction(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetRawTransferTransaction(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetRawBondTransaction(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetRawUnBondTransaction(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetRawWithdrawTransaction(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_TransactionServicer_to_server(servicer, server): + rpc_method_handlers = { + 'GetTransaction': grpc.unary_unary_rpc_method_handler( + servicer.GetTransaction, + request_deserializer=transaction__pb2.GetTransactionRequest.FromString, + response_serializer=transaction__pb2.GetTransactionResponse.SerializeToString, + ), + 'CalculateFee': grpc.unary_unary_rpc_method_handler( + servicer.CalculateFee, + request_deserializer=transaction__pb2.CalculateFeeRequest.FromString, + response_serializer=transaction__pb2.CalculateFeeResponse.SerializeToString, + ), + 'SendRawTransaction': grpc.unary_unary_rpc_method_handler( + servicer.SendRawTransaction, + request_deserializer=transaction__pb2.SendRawTransactionRequest.FromString, + response_serializer=transaction__pb2.SendRawTransactionResponse.SerializeToString, + ), + 'GetRawTransferTransaction': grpc.unary_unary_rpc_method_handler( + servicer.GetRawTransferTransaction, + request_deserializer=transaction__pb2.GetRawTransferTransactionRequest.FromString, + response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, + ), + 'GetRawBondTransaction': grpc.unary_unary_rpc_method_handler( + servicer.GetRawBondTransaction, + request_deserializer=transaction__pb2.GetRawBondTransactionRequest.FromString, + response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, + ), + 'GetRawUnBondTransaction': grpc.unary_unary_rpc_method_handler( + servicer.GetRawUnBondTransaction, + request_deserializer=transaction__pb2.GetRawUnBondTransactionRequest.FromString, + response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, + ), + 'GetRawWithdrawTransaction': grpc.unary_unary_rpc_method_handler( + servicer.GetRawWithdrawTransaction, + request_deserializer=transaction__pb2.GetRawWithdrawTransactionRequest.FromString, + response_serializer=transaction__pb2.GetRawTransactionResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'pactus.Transaction', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class Transaction(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def GetTransaction(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Transaction/GetTransaction', + transaction__pb2.GetTransactionRequest.SerializeToString, + transaction__pb2.GetTransactionResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def CalculateFee(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Transaction/CalculateFee', + transaction__pb2.CalculateFeeRequest.SerializeToString, + transaction__pb2.CalculateFeeResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def SendRawTransaction(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Transaction/SendRawTransaction', + transaction__pb2.SendRawTransactionRequest.SerializeToString, + transaction__pb2.SendRawTransactionResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetRawTransferTransaction(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Transaction/GetRawTransferTransaction', + transaction__pb2.GetRawTransferTransactionRequest.SerializeToString, + transaction__pb2.GetRawTransactionResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetRawBondTransaction(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Transaction/GetRawBondTransaction', + transaction__pb2.GetRawBondTransactionRequest.SerializeToString, + transaction__pb2.GetRawTransactionResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetRawUnBondTransaction(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Transaction/GetRawUnBondTransaction', + transaction__pb2.GetRawUnBondTransactionRequest.SerializeToString, + transaction__pb2.GetRawTransactionResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def GetRawWithdrawTransaction(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Transaction/GetRawWithdrawTransaction', + transaction__pb2.GetRawWithdrawTransactionRequest.SerializeToString, + transaction__pb2.GetRawTransactionResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/python/pactus/wallet_pb2.py b/python/pactus/wallet_pb2.py new file mode 100644 index 0000000..6738928 --- /dev/null +++ b/python/pactus/wallet_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: wallet.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cwallet.proto\x12\x06pactus\"}\n\x13\x43reateWalletRequest\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x1a\n\x08mnemonic\x18\x02 \x01(\tR\x08mnemonic\x12\x1a\n\x08language\x18\x03 \x01(\tR\x08language\x12\x1a\n\x08password\x18\x04 \x01(\tR\x08password\"\x16\n\x14\x43reateWalletResponse\"\'\n\x11LoadWalletRequest\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\"(\n\x12LoadWalletResponse\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\")\n\x13UnloadWalletRequest\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\"*\n\x14UnloadWalletResponse\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\"I\n\x11LockWalletRequest\x12\x1a\n\x08password\x18\x01 \x01(\tR\x08password\x12\x18\n\x07timeout\x18\x02 \x01(\x05R\x07timeout\"\x14\n\x12LockWalletResponse\"K\n\x13UnlockWalletRequest\x12\x1a\n\x08password\x18\x01 \x01(\tR\x08password\x12\x18\n\x07timeout\x18\x02 \x01(\x05R\x07timeout\"\x16\n\x14UnlockWalletResponse2\xf3\x02\n\x06Wallet\x12I\n\x0c\x43reateWallet\x12\x1b.pactus.CreateWalletRequest\x1a\x1c.pactus.CreateWalletResponse\x12\x43\n\nLoadWallet\x12\x19.pactus.LoadWalletRequest\x1a\x1a.pactus.LoadWalletResponse\x12I\n\x0cUnloadWallet\x12\x1b.pactus.UnloadWalletRequest\x1a\x1c.pactus.UnloadWalletResponse\x12\x43\n\nLockWallet\x12\x19.pactus.LockWalletRequest\x1a\x1a.pactus.LockWalletResponse\x12I\n\x0cUnlockWallet\x12\x1b.pactus.UnlockWalletRequest\x1a\x1c.pactus.UnlockWalletResponseBA\n\rpactus.walletZ0github.com/pactus-project/pactus/www/grpc/pactusb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wallet_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\rpactus.walletZ0github.com/pactus-project/pactus/www/grpc/pactus' + _CREATEWALLETREQUEST._serialized_start=24 + _CREATEWALLETREQUEST._serialized_end=149 + _CREATEWALLETRESPONSE._serialized_start=151 + _CREATEWALLETRESPONSE._serialized_end=173 + _LOADWALLETREQUEST._serialized_start=175 + _LOADWALLETREQUEST._serialized_end=214 + _LOADWALLETRESPONSE._serialized_start=216 + _LOADWALLETRESPONSE._serialized_end=256 + _UNLOADWALLETREQUEST._serialized_start=258 + _UNLOADWALLETREQUEST._serialized_end=299 + _UNLOADWALLETRESPONSE._serialized_start=301 + _UNLOADWALLETRESPONSE._serialized_end=343 + _LOCKWALLETREQUEST._serialized_start=345 + _LOCKWALLETREQUEST._serialized_end=418 + _LOCKWALLETRESPONSE._serialized_start=420 + _LOCKWALLETRESPONSE._serialized_end=440 + _UNLOCKWALLETREQUEST._serialized_start=442 + _UNLOCKWALLETREQUEST._serialized_end=517 + _UNLOCKWALLETRESPONSE._serialized_start=519 + _UNLOCKWALLETRESPONSE._serialized_end=541 + _WALLET._serialized_start=544 + _WALLET._serialized_end=915 +# @@protoc_insertion_point(module_scope) diff --git a/python/pactus/wallet_pb2_grpc.py b/python/pactus/wallet_pb2_grpc.py new file mode 100644 index 0000000..ca0d05e --- /dev/null +++ b/python/pactus/wallet_pb2_grpc.py @@ -0,0 +1,198 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +import wallet_pb2 as wallet__pb2 + + +class WalletStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.CreateWallet = channel.unary_unary( + '/pactus.Wallet/CreateWallet', + request_serializer=wallet__pb2.CreateWalletRequest.SerializeToString, + response_deserializer=wallet__pb2.CreateWalletResponse.FromString, + ) + self.LoadWallet = channel.unary_unary( + '/pactus.Wallet/LoadWallet', + request_serializer=wallet__pb2.LoadWalletRequest.SerializeToString, + response_deserializer=wallet__pb2.LoadWalletResponse.FromString, + ) + self.UnloadWallet = channel.unary_unary( + '/pactus.Wallet/UnloadWallet', + request_serializer=wallet__pb2.UnloadWalletRequest.SerializeToString, + response_deserializer=wallet__pb2.UnloadWalletResponse.FromString, + ) + self.LockWallet = channel.unary_unary( + '/pactus.Wallet/LockWallet', + request_serializer=wallet__pb2.LockWalletRequest.SerializeToString, + response_deserializer=wallet__pb2.LockWalletResponse.FromString, + ) + self.UnlockWallet = channel.unary_unary( + '/pactus.Wallet/UnlockWallet', + request_serializer=wallet__pb2.UnlockWalletRequest.SerializeToString, + response_deserializer=wallet__pb2.UnlockWalletResponse.FromString, + ) + + +class WalletServicer(object): + """Missing associated documentation comment in .proto file.""" + + def CreateWallet(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def LoadWallet(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def UnloadWallet(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def LockWallet(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def UnlockWallet(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_WalletServicer_to_server(servicer, server): + rpc_method_handlers = { + 'CreateWallet': grpc.unary_unary_rpc_method_handler( + servicer.CreateWallet, + request_deserializer=wallet__pb2.CreateWalletRequest.FromString, + response_serializer=wallet__pb2.CreateWalletResponse.SerializeToString, + ), + 'LoadWallet': grpc.unary_unary_rpc_method_handler( + servicer.LoadWallet, + request_deserializer=wallet__pb2.LoadWalletRequest.FromString, + response_serializer=wallet__pb2.LoadWalletResponse.SerializeToString, + ), + 'UnloadWallet': grpc.unary_unary_rpc_method_handler( + servicer.UnloadWallet, + request_deserializer=wallet__pb2.UnloadWalletRequest.FromString, + response_serializer=wallet__pb2.UnloadWalletResponse.SerializeToString, + ), + 'LockWallet': grpc.unary_unary_rpc_method_handler( + servicer.LockWallet, + request_deserializer=wallet__pb2.LockWalletRequest.FromString, + response_serializer=wallet__pb2.LockWalletResponse.SerializeToString, + ), + 'UnlockWallet': grpc.unary_unary_rpc_method_handler( + servicer.UnlockWallet, + request_deserializer=wallet__pb2.UnlockWalletRequest.FromString, + response_serializer=wallet__pb2.UnlockWalletResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'pactus.Wallet', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class Wallet(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def CreateWallet(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Wallet/CreateWallet', + wallet__pb2.CreateWalletRequest.SerializeToString, + wallet__pb2.CreateWalletResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def LoadWallet(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Wallet/LoadWallet', + wallet__pb2.LoadWalletRequest.SerializeToString, + wallet__pb2.LoadWalletResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def UnloadWallet(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Wallet/UnloadWallet', + wallet__pb2.UnloadWalletRequest.SerializeToString, + wallet__pb2.UnloadWalletResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def LockWallet(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Wallet/LockWallet', + wallet__pb2.LockWalletRequest.SerializeToString, + wallet__pb2.LockWalletResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def UnlockWallet(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/pactus.Wallet/UnlockWallet', + wallet__pb2.UnlockWalletRequest.SerializeToString, + wallet__pb2.UnlockWalletResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/python/public_key.py b/python/public_key.py new file mode 100644 index 0000000..e34aa29 --- /dev/null +++ b/python/public_key.py @@ -0,0 +1,50 @@ +import hashlib +from ripemd.ripemd160 import ripemd160 +import address +import utils + +PublicKeySize = 96 +PublicKeyHRP = "tpublic" +PublicKeyTypeBLS = 1 + + +class PublicKey: + def __init__(self, data=None): + if data is None: + self.data = bytearray(PublicKeySize) + else: + if len(data) != PublicKeySize: + raise ValueError("Public key data must be 96 bytes long") + self.data = bytearray(data) + + @classmethod + def from_string(cls, text): + hrp, typ, data = utils.decode_to_base256_with_type(text) + + if hrp != PublicKeyHRP: + raise ValueError(f"Invalid hrp: {hrp}") + + if typ != PublicKeyTypeBLS: + raise ValueError(f"Invalid public key type: {typ}") + + return cls(data) + + def bytes(self): + return self.data + + def string(self): + return utils.encode_from_base256_with_type(PublicKeyHRP, PublicKeyTypeBLS, self.data) + + def account_address(self): + return self._make_address(address.AddressType.BLSAccount) + + def validator_address(self): + return self._make_address(address.AddressType.Validator) + + def _make_address(self, address_type): + blake2b = hashlib.blake2b(digest_size=32) + blake2b.update(self.data) + hash_256 = blake2b.digest() + hash_160 = ripemd160(hash_256) + addr = address.Address(address_type, hash_160) + return addr diff --git a/python/test.py b/python/test.py new file mode 100644 index 0000000..f708a1d --- /dev/null +++ b/python/test.py @@ -0,0 +1,15 @@ +import unittest +import public_key + +class TestPublicKey(unittest.TestCase): + def test_from_string(self): + pubStr = "tpublic1pj2aecual5gul3p6epxw0pyulnpxtek3x20r2w5wkguxshfjqx7ecuzmgu0s9g2zkfz3hchasn0u6srwcvprweg20zjy9u5ehj8798lh3jakflaap77u8xqznpkgftg6emkxmg7g3v8052kfjjvtuasqsty299nxn" + addrAccStr = "tpc1zwmd7fr9muntueu9u0unduy8ycymzgthvu8tgyx" + addrValStr = "tpc1pwmd7fr9muntueu9u0unduy8ycymzgthvpvm4nm" + + pub = public_key.PublicKey.from_string(pubStr) + self.assertEqual(pub.account_address().string(), addrAccStr) + self.assertEqual(pub.validator_address().string(), addrValStr) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/python/utils.py b/python/utils.py new file mode 100644 index 0000000..3419841 --- /dev/null +++ b/python/utils.py @@ -0,0 +1,15 @@ +import bech32m +import hashlib +from ripemd.ripemd160 import ripemd160 + +def decode_to_base256_with_type(text): + (hrp, data, spec) = bech32m.bech32_decode(text) + assert spec == bech32m.Encoding.BECH32M + + regrouped = bech32m.convertbits(data[1:], 5, 8, False) + return (hrp, data[0], regrouped) + +def encode_from_base256_with_type(hrp, typ, data): + converted = bech32m.convertbits(list(data), 8, 5, True) + converted = [typ] + converted + return bech32m.bech32_encode(hrp, converted, bech32m.Encoding.BECH32M) \ No newline at end of file From 3244179919635639a56e549086b17d93783cb1a1 Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 15:45:21 +0000 Subject: [PATCH 16/30] feat: updating discord messages, adding memo to faucet bond transaction --- discord/discord.go | 36 +++++++++++++++++++----------------- wallet/wallet.go | 4 ++-- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index 18795f5..f293b07 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -108,8 +108,8 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { if strings.ToLower(m.Content) == "balance" { balance := b.faucetWallet.GetBalance() v, d := b.store.GetDistribution() - msg := p.Sprintf("Available faucet balance is %.4f test PACs\n", balance.Available) - msg += p.Sprintf("A total of %.4f test PACs has been distributed to %d validators\n", d, v) + msg := p.Sprintf("Available faucet balance is %.4f test tPAC's\n", balance.Available) + msg += p.Sprintf("A total of %.4f test tPAC's has been distributed to %d validators.\n", d, v) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -120,7 +120,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { lastBlockTimeFormatted := time.Unix(int64(lastBlockTime), 0) if (uint32(currentTime.Unix()) - lastBlockTime) > 15 { - msg := p.Sprintf("Network is unhealthy\nlast block time: %v\ncurrent time: %v\nDifference is more than 15 seconds.", + msg := p.Sprintf("Network is unhealthy\nLast block time: %v\nCurrent time: %v\nDifference is more than 15 seconds.", lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05")) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return @@ -182,7 +182,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { referrals := b.referralStore.GetAllReferrals() for _, r := range referrals { if r.DiscordID == m.Author.ID { - msg := fmt.Sprintf("Your referral data:\nPoints: %v (%v tPACs)\nCode: ```%v```\n", r.Points, (r.Points * 10), r.ReferralCode) + msg := fmt.Sprintf("Your referral information:\nPoints: %v (%v tPACs)\nCode: ```%v```\n", r.Points, (r.Points * 10), r.ReferralCode) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -202,7 +202,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } - msg := fmt.Sprintf("Your referral data:\nPoints: %v (%v tPACs)\nCode: ```%v```\n", 0, 0, referralCode) + msg := fmt.Sprintf("Your referral information:\nPoints: %v (%v tPAC's)\nCode: ```%v```\n", 0, 0, referralCode) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -212,7 +212,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { Params := strings.Split(trimmedPrefix, " ") if len(Params) != 2 { - msg := p.Sprintf("*Invalid* parameters!") + msg := p.Sprintf("Invalid parameters, referral code is missed!") _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -231,7 +231,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { } // validate referral. - _, found := b.referralStore.GetData(referralCode) + referral, found := b.referralStore.GetData(referralCode) if !found { msg := p.Sprintf("*Invalid* referral!") _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) @@ -254,7 +254,8 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { } // send faucet - txHashFaucet := b.faucetWallet.BondTransaction(pubKey, address, amount) + memo := fmt.Sprintf("pactus faucet ref:%v", referral.DiscordID) + txHashFaucet := b.faucetWallet.BondTransaction(pubKey, address, amount, memo) if txHashFaucet != "" { err := b.store.SetData(peerID, address, m.Author.Username, m.Author.ID, amount) @@ -262,8 +263,8 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { log.Printf("error saving faucet information: %v\n", err) } - msg := p.Sprintf("%v %.4f test PACs is staked to %v successfully!", - m.Author.Username, amount, address) + msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully!\n with %v as referral.", + m.Author.Username, amount, address, referral.DiscordName) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -293,13 +294,14 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { } // send faucet - txHash := b.faucetWallet.BondTransaction(pubKey, trimmedAddress, b.cfg.FaucetAmount) + memo := "pactus faucet" + txHash := b.faucetWallet.BondTransaction(pubKey, trimmedAddress, b.cfg.FaucetAmount, memo) if txHash != "" { err := b.store.SetData(peerID, trimmedAddress, m.Author.Username, m.Author.ID, b.cfg.FaucetAmount) if err != nil { log.Printf("error saving faucet information: %v\n", err) } - msg := p.Sprintf("%v %.4f test PACs is staked to %v successfully!", + msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully!", m.Author.Username, b.cfg.FaucetAmount, trimmedAddress) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) } @@ -342,8 +344,8 @@ func help(s *discordgo.Session, m *discordgo.MessageCreate) { "To get network health status, simply type: `health`\n" + "To get peer information, simply type: `peer-info [validator address]`\n" + "To get your referral information, simply type: `my-referral`\n" + - "To request faucet for test network *with referral code*: simply type `faucet-referral [validator address] [referral code]`\n" + - "To request faucet for test network: simply type `faucet [validator address]`.", + "To request faucet for test network *with referral code*: simply type `faucet-referral [validator address] [referral code]` referral faucet will get 100 tPAC's\n" + + "To request faucet for test network: simply type `faucet [validator address]`. normal faucet will get 60 tPAC's", Fields: []*discordgo.MessageEmbedField{ { Name: "Example of requesting `faucet` ", @@ -419,16 +421,16 @@ func (b *Bot) validateInfo(address, discordID string) (string, string, bool, str } func (b *Bot) networkInfo() string { - msg := "Pactus is truly decentralised proof of stake blockchain." + msg := "Pactus is truly decentralized Proof of Stake blockchain." nodes, err := b.cm.GetNetworkInfo() if err != nil { log.Printf("error establishing connection") return msg } - msg += "\nThe following are the currentl statistics:\n" + msg += "\nThe current statistics are:\n" msg += fmt.Sprintf("Network started at : %v\n", time.UnixMilli(nodes.StartedAt*1000).Format("02/01/2006, 15:04:05")) msg += fmt.Sprintf("Total bytes sent : %v\n", uint32(nodes.TotalSentBytes)) - msg += fmt.Sprintf("Total received bytes : %v\n", uint32(nodes.TotalReceivedBytes)) + msg += fmt.Sprintf("Total bytes received : %v\n", uint32(nodes.TotalReceivedBytes)) msg += fmt.Sprintf("Number of peer nodes: %v\n", len(nodes.Peers)) // check block height blockchainInfo, err := b.cm.GetBlockchainInfo() diff --git a/wallet/wallet.go b/wallet/wallet.go index c860d21..92d0cfc 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -40,10 +40,10 @@ func Open(cfg *config.Config) *Wallet { return nil } -func (w *Wallet) BondTransaction(pubKey, toAddress string, amount float64) string { +func (w *Wallet) BondTransaction(pubKey, toAddress string, amount float64, memo string) string { opts := []pwallet.TxOption{ pwallet.OptionFee(util.CoinToChange(0)), - pwallet.OptionMemo("Faucet from PactusBot"), + pwallet.OptionMemo(memo), } tx, err := w.wallet.MakeBondTx(w.address, toAddress, pubKey, util.CoinToChange(amount), opts...) From 00149c3ccc561e88f7581d92453df2e2c5ad704e Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 16:06:20 +0000 Subject: [PATCH 17/30] feat: updating discord messages --- discord/discord.go | 99 +++++++++++++++++++++++++--------------------- wallet/wallet.go | 10 ++--- 2 files changed, 59 insertions(+), 50 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index f293b07..09144e2 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -108,7 +108,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { if strings.ToLower(m.Content) == "balance" { balance := b.faucetWallet.GetBalance() v, d := b.store.GetDistribution() - msg := p.Sprintf("Available faucet balance is %.4f test tPAC's\n", balance.Available) + msg := p.Sprintf("Available faucet balance is %.4f test tPAC's🪙\n", balance.Available) msg += p.Sprintf("A total of %.4f test tPAC's has been distributed to %d validators.\n", d, v) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return @@ -120,13 +120,13 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { lastBlockTimeFormatted := time.Unix(int64(lastBlockTime), 0) if (uint32(currentTime.Unix()) - lastBlockTime) > 15 { - msg := p.Sprintf("Network is unhealthy\nLast block time: %v\nCurrent time: %v\nDifference is more than 15 seconds.", + msg := p.Sprintf("Network is **unhealthy❌**\nLast block time⛓️: %v\nCurrent time🕧: %v\nDifference is more than 15 seconds.", lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05")) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } - msg := p.Sprintf("Network is **healthy**\nlast block time: %v\ncurrent time: %v\nDifference is less than 15 seconds.", + msg := p.Sprintf("Network is **healthy✅**\nLast block time⛓️: %v\nCurrent time🕧: %v\nDifference is less than 15 seconds.", lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05")) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return @@ -202,7 +202,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } - msg := fmt.Sprintf("Your referral information:\nPoints: %v (%v tPAC's)\nCode: ```%v```\n", 0, 0, referralCode) + msg := fmt.Sprintf("Your referral information👥:\nPoints: %v (%v tPAC's)\nCode: ```%v```\n", 0, 0, referralCode) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -255,19 +255,23 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { // send faucet memo := fmt.Sprintf("pactus faucet ref:%v", referral.DiscordID) - txHashFaucet := b.faucetWallet.BondTransaction(pubKey, address, amount, memo) - - if txHashFaucet != "" { - err := b.store.SetData(peerID, address, m.Author.Username, m.Author.ID, amount) - if err != nil { - log.Printf("error saving faucet information: %v\n", err) - } - - msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully!\n with %v as referral.", - m.Author.Username, amount, address, referral.DiscordName) + txHashFaucet, err := b.faucetWallet.BondTransaction(pubKey, address, amount, memo) + if err != nil { + msg := p.Sprintf("error while sending bond transaction: %w", err.Error()) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } + + err = b.store.SetData(peerID, address, m.Author.Username, m.Author.ID, amount) + if err != nil { + log.Printf("error saving faucet information: %v\n", err) + } + + msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\n with %v as referral.\n your transaction hash:%v", + m.Author.Username, amount, address, referral.DiscordName, txHashFaucet) + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } } @@ -295,31 +299,36 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { // send faucet memo := "pactus faucet" - txHash := b.faucetWallet.BondTransaction(pubKey, trimmedAddress, b.cfg.FaucetAmount, memo) - if txHash != "" { - err := b.store.SetData(peerID, trimmedAddress, m.Author.Username, m.Author.ID, b.cfg.FaucetAmount) - if err != nil { - log.Printf("error saving faucet information: %v\n", err) - } - msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully!", - m.Author.Username, b.cfg.FaucetAmount, trimmedAddress) + txHash, err := b.faucetWallet.BondTransaction(pubKey, trimmedAddress, b.cfg.FaucetAmount, memo) + if err != nil { + msg := p.Sprintf("error while sending bond transaction: %w", err.Error()) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + return + } + + err = b.store.SetData(peerID, trimmedAddress, m.Author.Username, m.Author.ID, b.cfg.FaucetAmount) + if err != nil { + log.Printf("error saving faucet information: %v\n", err) } + msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\nyour transaction hash:%v", + m.Author.Username, b.cfg.FaucetAmount, trimmedAddress, txHash) + _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) + } } if strings.Contains(strings.ToLower(m.Content), "tx-data") { - trimmedPrefix := strings.TrimPrefix(strings.ToLower(m.Content), "peer-info") + trimmedPrefix := strings.TrimPrefix(strings.ToLower(m.Content), "tx-data") trimmedTXHash := strings.Trim(trimmedPrefix, " ") data, err := b.cm.GetRandomClient().TransactionData(trimmedTXHash) if err != nil { - msg := p.Sprintf("An error occurred %v\n", err) + msg := p.Sprintf("An error occurred %v❌\n", err) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } - msg := p.Sprintf("your transaction data:\ndata:%v\nversion:%v\nlockTime:%v\nvalue:%v\nmemo:%v\npublic-key:%v\n", + msg := p.Sprintf("Your transaction data:\nData:%v\nVersion:%v\nLockTime:%v\nValue:%v\nMemo:%v\nPublic-key:%v\n", string(data.Data), data.Version, data.LockTime, data.Value, data.Memo, data.PublicKey) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return @@ -344,7 +353,7 @@ func help(s *discordgo.Session, m *discordgo.MessageCreate) { "To get network health status, simply type: `health`\n" + "To get peer information, simply type: `peer-info [validator address]`\n" + "To get your referral information, simply type: `my-referral`\n" + - "To request faucet for test network *with referral code*: simply type `faucet-referral [validator address] [referral code]` referral faucet will get 100 tPAC's\n" + + "To request faucet for test network *with referral code*: simply type `faucet-referral [validator address] [referral code]`\nreferral faucet will get 100 tPAC's\n" + "To request faucet for test network: simply type `faucet [validator address]`. normal faucet will get 60 tPAC's", Fields: []*discordgo.MessageEmbedField{ { @@ -359,7 +368,7 @@ func (b *Bot) validateInfo(address, discordID string) (string, string, bool, str _, err := crypto.AddressFromString(address) if err != nil { log.Printf("invalid address") - return "", "", false, "Pactus Universal Robot is unable to handle your request." + + return "", "", false, "Pactus Universal Robot is unable to handle your request.❌" + " If you are requesting testing faucet, supply the valid address." } @@ -376,7 +385,7 @@ func (b *Bot) validateInfo(address, discordID string) (string, string, bool, str } if isValidator { - return "", "", false, "Sorry. Your address is in the list of active validators. You do not need faucet again." + return "", "", false, "Sorry. Your address is in the list of active validators. You do not need faucet again.❌" } peerInfo, pub, err := b.cm.GetPeerInfo(address) @@ -385,8 +394,8 @@ func (b *Bot) validateInfo(address, discordID string) (string, string, bool, str } if pub == nil { log.Printf("error getting peer info") - return "", "", false, "Your node information could not obtained." + - " Make sure your node is fully synced before requesting the faucet." + return "", "", false, "Your node information could not obtained.❌" + + " Make sure your node is fully synced before requesting the faucet.🛜" } // check if the validator has already been given the faucet @@ -396,8 +405,8 @@ func (b *Bot) validateInfo(address, discordID string) (string, string, bool, str } if peerID.String() == "" { log.Printf("error getting peer id") - return "", "", false, "Your node information could not obtained." + - " Make sure your node is fully synced before requesting the faucet." + return "", "", false, "Your node information could not obtained.❌" + + " Make sure your node is fully synced before requesting the faucet.🛜" } v, exists = b.store.GetData(peerID.String()) if exists || v != nil { @@ -408,11 +417,11 @@ func (b *Bot) validateInfo(address, discordID string) (string, string, bool, str // height, err := cl.GetBlockchainHeight() // if err != nil { // log.Printf("error current block height") - // return "", "", false, "The bot cannot establish connection to the blochain network. Try again later." + // return "", "", false, "The bot cannot establish connection to the blockchain network. Try again later." // } // if (height - peerInfo.Height) > 1080 { - // msg := fmt.Sprintf("Your node is not fully synchronised. It is is behind by %v blocks." + - // " Make sure that your node is fully synchronised before requesting faucet.", (height - peerInfo.Height)) + // msg := fmt.Sprintf("Your node is not fully synchronized. It is is behind by %v blocks." + + // " Make sure that your node is fully synchronized before requesting faucet.", (height - peerInfo.Height)) // log.Printf("peer %s with address %v is not well synced: ", peerInfo.PeerId, address) // return "", "", false, msg @@ -421,27 +430,27 @@ func (b *Bot) validateInfo(address, discordID string) (string, string, bool, str } func (b *Bot) networkInfo() string { - msg := "Pactus is truly decentralized Proof of Stake blockchain." + msg := "Pactus is truly decentralized Proof of Stake Blockchain.⛓️" nodes, err := b.cm.GetNetworkInfo() if err != nil { log.Printf("error establishing connection") return msg } - msg += "\nThe current statistics are:\n" - msg += fmt.Sprintf("Network started at : %v\n", time.UnixMilli(nodes.StartedAt*1000).Format("02/01/2006, 15:04:05")) - msg += fmt.Sprintf("Total bytes sent : %v\n", uint32(nodes.TotalSentBytes)) - msg += fmt.Sprintf("Total bytes received : %v\n", uint32(nodes.TotalReceivedBytes)) - msg += fmt.Sprintf("Number of peer nodes: %v\n", len(nodes.Peers)) + msg += "\n📊 The current statistics are:\n" + msg += fmt.Sprintf("🕧Network started at: %v\n", time.UnixMilli(nodes.StartedAt*1000).Format("02/01/2006, 15:04:05")) + msg += fmt.Sprintf("⬆️Total bytes sent: %v\n", uint32(nodes.TotalSentBytes)) + msg += fmt.Sprintf("⬇️Total bytes received: %v\n", uint32(nodes.TotalReceivedBytes)) + msg += fmt.Sprintf("👾Number of peer nodes: %v\n", len(nodes.Peers)) // check block height blockchainInfo, err := b.cm.GetBlockchainInfo() if err != nil { log.Printf("error current block height") return msg } - msg += fmt.Sprintf("Block height: %v\n", blockchainInfo.LastBlockHeight) - msg += fmt.Sprintf("Total power: %.4f PACs\n", util.ChangeToCoin(blockchainInfo.TotalPower)) - msg += fmt.Sprintf("Total committee power: %.4f PACs\n", util.ChangeToCoin(blockchainInfo.CommitteePower)) - msg += fmt.Sprintf("Total validators: %v\n", blockchainInfo.TotalValidators) + msg += fmt.Sprintf("⛓️Block height: %v\n", blockchainInfo.LastBlockHeight) + msg += fmt.Sprintf("🦾Total power: %.4f PACs\n", util.ChangeToCoin(blockchainInfo.TotalPower)) + msg += fmt.Sprintf("🦾Total committee power: %.4f PACs\n", util.ChangeToCoin(blockchainInfo.CommitteePower)) + msg += fmt.Sprintf("✔️Total validators: %v\n", blockchainInfo.TotalValidators) return msg } diff --git a/wallet/wallet.go b/wallet/wallet.go index 92d0cfc..f30e25c 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -40,7 +40,7 @@ func Open(cfg *config.Config) *Wallet { return nil } -func (w *Wallet) BondTransaction(pubKey, toAddress string, amount float64, memo string) string { +func (w *Wallet) BondTransaction(pubKey, toAddress string, amount float64, memo string) (string, error) { opts := []pwallet.TxOption{ pwallet.OptionFee(util.CoinToChange(0)), pwallet.OptionMemo(memo), @@ -49,27 +49,27 @@ func (w *Wallet) BondTransaction(pubKey, toAddress string, amount float64, memo util.CoinToChange(amount), opts...) if err != nil { log.Printf("error creating bond transaction: %v", err) - return "" + return "", err } // sign transaction err = w.wallet.SignTransaction(w.password, tx) if err != nil { log.Printf("error signing bond transaction: %v", err) - return "" + return "", err } // broadcast transaction res, err := w.wallet.BroadcastTransaction(tx) if err != nil { log.Printf("error broadcasting bond transaction: %v", err) - return "" + return "", err } err = w.wallet.Save() if err != nil { log.Printf("error saving wallet transaction history: %v", err) } - return res // return transaction hash + return res, nil // return transaction hash } func (w *Wallet) GetBalance() *Balance { From 3fd74f1616a2c1ca470a4058c4226419f39659ac Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 16:39:42 +0000 Subject: [PATCH 18/30] feat: enhancing tx hash in faucet message --- discord/discord.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index 09144e2..c5b87cf 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -267,7 +267,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { log.Printf("error saving faucet information: %v\n", err) } - msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\n with %v as referral.\n your transaction hash:%v", + msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\n with %v as referral.\nYour transaction hash: ```%v```", m.Author.Username, amount, address, referral.DiscordName, txHashFaucet) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return @@ -310,7 +310,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { if err != nil { log.Printf("error saving faucet information: %v\n", err) } - msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\nyour transaction hash:%v", + msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\nYour transaction hash: ```%v```", m.Author.Username, b.cfg.FaucetAmount, trimmedAddress, txHash) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) From 0e3ce84ab557790357174ec79e66467a1e2721da Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 16:44:40 +0000 Subject: [PATCH 19/30] feat: enhancing messages --- Makefile | 2 +- discord/discord.go | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index 3fe8035..086b75a 100644 --- a/Makefile +++ b/Makefile @@ -31,6 +31,6 @@ check: golangci-lint run --build-tags "${BUILD_TAG}" --timeout=20m0s ### building -build-discord-bot: +discord-bot: go build -o build/main cmd/app.go \ No newline at end of file diff --git a/discord/discord.go b/discord/discord.go index c5b87cf..501dd24 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -119,15 +119,16 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { lastBlockTime := b.cm.GetLastBlockTime() lastBlockTimeFormatted := time.Unix(int64(lastBlockTime), 0) - if (uint32(currentTime.Unix()) - lastBlockTime) > 15 { - msg := p.Sprintf("Network is **unhealthy❌**\nLast block time⛓️: %v\nCurrent time🕧: %v\nDifference is more than 15 seconds.", - lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05")) + timeDiff := (uint32(currentTime.Unix()) - lastBlockTime) + if timeDiff> 15 { + msg := p.Sprintf("Network is **unhealthy❌**\nLast block time⛓️: %v\nCurrent time🕧: %v\nTime Difference: %v\nDifference is more than 15 seconds.", + lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05"), timeDiff) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } - msg := p.Sprintf("Network is **healthy✅**\nLast block time⛓️: %v\nCurrent time🕧: %v\nDifference is less than 15 seconds.", - lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05")) + msg := p.Sprintf("Network is **healthy✅**\nLast block time⛓️: %v\nCurrent time🕧: %v\nTime Difference: %v\nDifference is less than 15 seconds.", + lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05"), timeDiff) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -182,7 +183,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { referrals := b.referralStore.GetAllReferrals() for _, r := range referrals { if r.DiscordID == m.Author.ID { - msg := fmt.Sprintf("Your referral information:\nPoints: %v (%v tPACs)\nCode: ```%v```\n", r.Points, (r.Points * 10), r.ReferralCode) + msg := fmt.Sprintf("Your referral information👥:\nPoints: %v (%v tPACs)\nCode: ```%v```\n", r.Points, (r.Points * 10), r.ReferralCode) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } @@ -242,7 +243,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { // check available balance balance := b.faucetWallet.GetBalance() if balance.Available < b.cfg.FaucetAmount { - _, _ = s.ChannelMessageSendReply(m.ChannelID, "Insufficient faucet balance. Try again later.", m.Reference()) + _, _ = s.ChannelMessageSendReply(m.ChannelID, "Insufficient faucet balance. Try again later please😔.", m.Reference()) return } From 55b4ec0f2d13cd04cc3e4cf5589c3815c0eeac5b Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 16:51:58 +0000 Subject: [PATCH 20/30] chore: else if for facuet command --- discord/discord.go | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index 501dd24..efba095 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -120,14 +120,14 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { lastBlockTimeFormatted := time.Unix(int64(lastBlockTime), 0) timeDiff := (uint32(currentTime.Unix()) - lastBlockTime) - if timeDiff> 15 { - msg := p.Sprintf("Network is **unhealthy❌**\nLast block time⛓️: %v\nCurrent time🕧: %v\nTime Difference: %v\nDifference is more than 15 seconds.", + if timeDiff > 15 { + msg := p.Sprintf("Network is **unhealthy❌**\nLast block time⛓️: %v\nCurrent time🕧: %v\nTime Difference: %v seconds\nDifference is more than 15 seconds.", lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05"), timeDiff) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } - msg := p.Sprintf("Network is **healthy✅**\nLast block time⛓️: %v\nCurrent time🕧: %v\nTime Difference: %v\nDifference is less than 15 seconds.", + msg := p.Sprintf("Network is **healthy✅**\nLast block time⛓️: %v\nCurrent time🕧: %v\nTime Difference: %v seconds\nDifference is less than 15 seconds.", lastBlockTimeFormatted.Format("02/01/2006, 15:04:05"), currentTime.Format("02/01/2006, 15:04:05"), timeDiff) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return @@ -274,9 +274,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } - } - - if strings.Contains(strings.ToLower(m.Content), "faucet") { + } else if strings.Contains(strings.ToLower(m.Content), "faucet") { trimmedPrefix := strings.TrimPrefix(strings.ToLower(m.Content), "faucet") // faucet message must contain address/public-key trimmedAddress := strings.Trim(trimmedPrefix, " ") From 02f38f0d042a8f5b2df0bb2e5533da8de9fda4c2 Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 17:06:42 +0000 Subject: [PATCH 21/30] fix: fixing add point fucntion issue --- discord/referral.go | 46 +++++++++++++++++++++------------------------ 1 file changed, 21 insertions(+), 25 deletions(-) diff --git a/discord/referral.go b/discord/referral.go index 946e372..bfef9ba 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -95,31 +95,27 @@ func (rs *ReferralStore) GetAllReferrals() []*Referral { // AddPoint add one point for a referral. func (rs *ReferralStore) AddPoint(code string) bool { - entry, found := rs.syncMap.Load(code) - if !found { - return false - } - - if found { - referral := entry.(*Referral) - referral.Points++ - rs.syncMap.Store(referral.ReferralCode, referral) - return true - } - - // save record - data, err := marshaReferralJSON(rs.syncMap) - if err != nil { - log.Printf("error marshalling validator data file: %v", err) - return false - } - - if err := os.WriteFile(rs.cfg.ReferralDataPath, data, 0o600); err != nil { - log.Printf("failed to write to %s: %v", rs.cfg.ReferralDataPath, err) - return false - } - - return false + entry, found := rs.syncMap.Load(code) + if !found { + return false + } + referral := entry.(*Referral) + referral.Points++ + rs.syncMap.Store(referral.ReferralCode, referral) + + // save record + data, err := marshaReferralJSON(rs.syncMap) + if err != nil { + log.Printf("error marshalling validator data file: %v", err) + return false + } + + if err := os.WriteFile(rs.cfg.ReferralDataPath, data, 0o600); err != nil { + log.Printf("failed to write to %s: %v", rs.cfg.ReferralDataPath, err) + return false + } + + return true } func marshaReferralJSON(m *sync.Map) ([]byte, error) { From 3ec768b80d7f9062c85df14202d380d7559437f8 Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 17:09:57 +0000 Subject: [PATCH 22/30] fix: referral store messages update --- discord/referral.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/discord/referral.go b/discord/referral.go index bfef9ba..88be474 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -26,7 +26,7 @@ type ReferralStore struct { func LoadReferralData(cfg *config.Config) (*ReferralStore, error) { file, err := os.ReadFile(cfg.ReferralDataPath) if err != nil { - log.Printf("error loading validator data: %v", err) + log.Printf("error loading referral data: %v", err) return nil, fmt.Errorf("error loading data file: %w", err) } if len(file) == 0 { @@ -39,8 +39,8 @@ func LoadReferralData(cfg *config.Config) (*ReferralStore, error) { data, err := unmarshalReferralJSON(file) if err != nil { - log.Printf("error unmarshalling validator data: %v", err) - return nil, fmt.Errorf("error unmarshalling validator data: %w", err) + log.Printf("error unmarshalling referral data: %v", err) + return nil, fmt.Errorf("error unmarshalling referral data: %w", err) } rs := &ReferralStore{ syncMap: data, @@ -60,8 +60,8 @@ func (rs *ReferralStore) NewReferral(discordId, discordName, referralCode string // save record data, err := marshaReferralJSON(rs.syncMap) if err != nil { - log.Printf("error marshalling validator data file: %v", err) - return fmt.Errorf("error marshalling validator data file: %w", err) + log.Printf("error marshalling referral data file: %v", err) + return fmt.Errorf("error marshalling referral data file: %w", err) } if err := os.WriteFile(rs.cfg.ReferralDataPath, data, 0o600); err != nil { log.Printf("failed to write to %s: %v", rs.cfg.ReferralDataPath, err) @@ -106,7 +106,7 @@ func (rs *ReferralStore) AddPoint(code string) bool { // save record data, err := marshaReferralJSON(rs.syncMap) if err != nil { - log.Printf("error marshalling validator data file: %v", err) + log.Printf("error marshalling referral data file: %v", err) return false } From 7a9718927156052d6fe0c659b381865860a53294 Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 17:20:03 +0000 Subject: [PATCH 23/30] fix: referral store messages update --- discord/referral.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/discord/referral.go b/discord/referral.go index 88be474..ece38b2 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -99,11 +99,13 @@ func (rs *ReferralStore) AddPoint(code string) bool { if !found { return false } + + // updating record referral := entry.(*Referral) referral.Points++ rs.syncMap.Store(referral.ReferralCode, referral) - // save record + // saving record data, err := marshaReferralJSON(rs.syncMap) if err != nil { log.Printf("error marshalling referral data file: %v", err) From f84e22cf1f99efaf69be9703fe551e6e939f3363 Mon Sep 17 00:00:00 2001 From: Kay Date: Tue, 19 Dec 2023 19:15:48 +0000 Subject: [PATCH 24/30] fix: typo --- discord/discord.go | 4 ++-- discord/referral.go | 42 +++++++++++++++++++++--------------------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index efba095..e75467c 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -108,8 +108,8 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { if strings.ToLower(m.Content) == "balance" { balance := b.faucetWallet.GetBalance() v, d := b.store.GetDistribution() - msg := p.Sprintf("Available faucet balance is %.4f test tPAC's🪙\n", balance.Available) - msg += p.Sprintf("A total of %.4f test tPAC's has been distributed to %d validators.\n", d, v) + msg := p.Sprintf("Available faucet balance is %.4f tPAC's🪙\n", balance.Available) + msg += p.Sprintf("A total of %.4f tPAC's has been distributed to %d validators.\n", d, v) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return } diff --git a/discord/referral.go b/discord/referral.go index ece38b2..7fce6ae 100644 --- a/discord/referral.go +++ b/discord/referral.go @@ -95,29 +95,29 @@ func (rs *ReferralStore) GetAllReferrals() []*Referral { // AddPoint add one point for a referral. func (rs *ReferralStore) AddPoint(code string) bool { - entry, found := rs.syncMap.Load(code) - if !found { - return false - } + entry, found := rs.syncMap.Load(code) + if !found { + return false + } // updating record - referral := entry.(*Referral) - referral.Points++ - rs.syncMap.Store(referral.ReferralCode, referral) - - // saving record - data, err := marshaReferralJSON(rs.syncMap) - if err != nil { - log.Printf("error marshalling referral data file: %v", err) - return false - } - - if err := os.WriteFile(rs.cfg.ReferralDataPath, data, 0o600); err != nil { - log.Printf("failed to write to %s: %v", rs.cfg.ReferralDataPath, err) - return false - } - - return true + referral := entry.(*Referral) + referral.Points++ + rs.syncMap.Store(referral.ReferralCode, referral) + + // saving record + data, err := marshaReferralJSON(rs.syncMap) + if err != nil { + log.Printf("error marshalling referral data file: %v", err) + return false + } + + if err := os.WriteFile(rs.cfg.ReferralDataPath, data, 0o600); err != nil { + log.Printf("failed to write to %s: %v", rs.cfg.ReferralDataPath, err) + return false + } + + return true } func marshaReferralJSON(m *sync.Map) ([]byte, error) { From 5fdad8a1682e589ec722604b22e69c84292f1900 Mon Sep 17 00:00:00 2001 From: Kay Date: Wed, 20 Dec 2023 14:54:46 +0000 Subject: [PATCH 25/30] feat: adding referrer discord ID to validator strcut (#11) --- discord/discord.go | 4 ++-- discord/store.go | 12 +++++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index e75467c..941150a 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -263,7 +263,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } - err = b.store.SetData(peerID, address, m.Author.Username, m.Author.ID, amount) + err = b.store.SetData(peerID, address, m.Author.Username, m.Author.ID, referral.DiscordID, amount) if err != nil { log.Printf("error saving faucet information: %v\n", err) } @@ -305,7 +305,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } - err = b.store.SetData(peerID, trimmedAddress, m.Author.Username, m.Author.ID, b.cfg.FaucetAmount) + err = b.store.SetData(peerID, trimmedAddress, m.Author.Username, m.Author.ID, "", b.cfg.FaucetAmount) if err != nil { log.Printf("error saving faucet information: %v\n", err) } diff --git a/discord/store.go b/discord/store.go index 7ac9ae7..3f9809f 100644 --- a/discord/store.go +++ b/discord/store.go @@ -12,10 +12,11 @@ import ( // Validator is a value stored in the cache. type Validator struct { - DiscordName string `json:"discord_name"` - DiscordID string `json:"discord_id"` - ValidatorAddress string `json:"validator_address"` - FaucetAmount float64 `json:"faucet_amount"` + DiscordName string `json:"discord_name"` + DiscordID string `json:"discord_id"` + ValidatorAddress string `json:"validator_address"` + ReferrerDiscordID string `json:"referrer_discord_id"` + FaucetAmount float64 `json:"faucet_amount"` } type ValidatorRoundOne struct { @@ -61,10 +62,11 @@ func LoadData(cfg *config.Config) (*SafeStore, error) { } // SetData Set a given value to the data storage. -func (ss *SafeStore) SetData(peerID, address, discordName, discordID string, amount float64) error { +func (ss *SafeStore) SetData(peerID, address, discordName, discordID, referrerDiscordID string, amount float64) error { ss.syncMap.Store(peerID, &Validator{ DiscordName: discordName, DiscordID: discordID, ValidatorAddress: address, FaucetAmount: amount, + ReferrerDiscordID: referrerDiscordID, }) // save record data, err := marshalJSON(ss.syncMap) From 48d228694b1f0e80c086413db20b96864c6fa8dc Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 21 Dec 2023 06:47:24 +0000 Subject: [PATCH 26/30] feat: adding pactusscan transaction link --- discord/discord.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index 941150a..24007c1 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -268,7 +268,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { log.Printf("error saving faucet information: %v\n", err) } - msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\n with %v as referral.\nYour transaction hash: ```%v```", + msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\n with %v as referral.\nYour transaction:\nhttps://pacscan.org/transactions/%v/", m.Author.Username, amount, address, referral.DiscordName, txHashFaucet) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) return @@ -309,7 +309,7 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { if err != nil { log.Printf("error saving faucet information: %v\n", err) } - msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\nYour transaction hash: ```%v```", + msg := p.Sprintf("%v %.4f tPAC's is staked to %v successfully🪙!\nYour transaction:\nhttps://pacscan.org/transactions/%v/", m.Author.Username, b.cfg.FaucetAmount, trimmedAddress, txHash) _, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference()) From ed710ccb46c30296fb4b9fb36718d1d312e8760b Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 21 Dec 2023 13:02:04 +0000 Subject: [PATCH 27/30] feat: adding top10 referral script --- .gitignore | 4 +- scripts/go/main.go | 58 +++++++++++++++++++ {python => scripts/python}/address.py | 0 {python => scripts/python}/bech32m.py | 0 {python => scripts/python}/main.py | 0 {python => scripts/python}/network_pb2.py | 0 .../python}/network_pb2_grpc.py | 0 .../python}/pactus/blockchain_pb2.py | 0 .../python}/pactus/blockchain_pb2_grpc.py | 0 .../python}/pactus/network_pb2.py | 0 .../python}/pactus/network_pb2_grpc.py | 0 .../python}/pactus/transaction_pb2.py | 0 .../python}/pactus/transaction_pb2_grpc.py | 0 .../python}/pactus/wallet_pb2.py | 0 .../python}/pactus/wallet_pb2_grpc.py | 0 {python => scripts/python}/public_key.py | 0 {python => scripts/python}/test.py | 0 {python => scripts/python}/utils.py | 0 18 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 scripts/go/main.go rename {python => scripts/python}/address.py (100%) rename {python => scripts/python}/bech32m.py (100%) rename {python => scripts/python}/main.py (100%) rename {python => scripts/python}/network_pb2.py (100%) rename {python => scripts/python}/network_pb2_grpc.py (100%) rename {python => scripts/python}/pactus/blockchain_pb2.py (100%) rename {python => scripts/python}/pactus/blockchain_pb2_grpc.py (100%) rename {python => scripts/python}/pactus/network_pb2.py (100%) rename {python => scripts/python}/pactus/network_pb2_grpc.py (100%) rename {python => scripts/python}/pactus/transaction_pb2.py (100%) rename {python => scripts/python}/pactus/transaction_pb2_grpc.py (100%) rename {python => scripts/python}/pactus/wallet_pb2.py (100%) rename {python => scripts/python}/pactus/wallet_pb2_grpc.py (100%) rename {python => scripts/python}/public_key.py (100%) rename {python => scripts/python}/test.py (100%) rename {python => scripts/python}/utils.py (100%) diff --git a/.gitignore b/.gitignore index 155658d..80960cf 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,6 @@ cmd/data/wallet.json cmd/data/config.json cmd/data/validators.json cmd/bin -__pycache__ \ No newline at end of file +__pycache__ +/scripts/go/referral.json +/scripts/go/top10.json diff --git a/scripts/go/main.go b/scripts/go/main.go new file mode 100644 index 0000000..6f6ba8a --- /dev/null +++ b/scripts/go/main.go @@ -0,0 +1,58 @@ +package main + +import ( + "encoding/json" + "os" + "sort" + + "github.com/kehiy/RoboPac/discord" +) + +func main() { + referrals, err := LoadReferralData("./referral.json") + if err != nil { + panic(err) + } + + sort.Slice(referrals, func(i, j int) bool { // sort referrals based on points in descending order + return referrals[i].Points > referrals[j].Points + }) + + top10 := [10]discord.Referral{} + for i, r := range referrals { + if i >= 10 { + break + } + top10[i] = r + } + + data, err := json.Marshal(top10) + if err != nil { + panic(err) + } + + err = os.WriteFile("top10.json", data, 0o600) + if err != nil { + panic(err) + } +} + +func LoadReferralData(path string) ([]discord.Referral, error) { + file, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + referrals := map[string]discord.Referral{} + err = json.Unmarshal(file, &referrals) + if err != nil { + return nil, err + } + + result := []discord.Referral{} + for _, r := range referrals { + result = append(result, r) + } + + return result, nil +} diff --git a/python/address.py b/scripts/python/address.py similarity index 100% rename from python/address.py rename to scripts/python/address.py diff --git a/python/bech32m.py b/scripts/python/bech32m.py similarity index 100% rename from python/bech32m.py rename to scripts/python/bech32m.py diff --git a/python/main.py b/scripts/python/main.py similarity index 100% rename from python/main.py rename to scripts/python/main.py diff --git a/python/network_pb2.py b/scripts/python/network_pb2.py similarity index 100% rename from python/network_pb2.py rename to scripts/python/network_pb2.py diff --git a/python/network_pb2_grpc.py b/scripts/python/network_pb2_grpc.py similarity index 100% rename from python/network_pb2_grpc.py rename to scripts/python/network_pb2_grpc.py diff --git a/python/pactus/blockchain_pb2.py b/scripts/python/pactus/blockchain_pb2.py similarity index 100% rename from python/pactus/blockchain_pb2.py rename to scripts/python/pactus/blockchain_pb2.py diff --git a/python/pactus/blockchain_pb2_grpc.py b/scripts/python/pactus/blockchain_pb2_grpc.py similarity index 100% rename from python/pactus/blockchain_pb2_grpc.py rename to scripts/python/pactus/blockchain_pb2_grpc.py diff --git a/python/pactus/network_pb2.py b/scripts/python/pactus/network_pb2.py similarity index 100% rename from python/pactus/network_pb2.py rename to scripts/python/pactus/network_pb2.py diff --git a/python/pactus/network_pb2_grpc.py b/scripts/python/pactus/network_pb2_grpc.py similarity index 100% rename from python/pactus/network_pb2_grpc.py rename to scripts/python/pactus/network_pb2_grpc.py diff --git a/python/pactus/transaction_pb2.py b/scripts/python/pactus/transaction_pb2.py similarity index 100% rename from python/pactus/transaction_pb2.py rename to scripts/python/pactus/transaction_pb2.py diff --git a/python/pactus/transaction_pb2_grpc.py b/scripts/python/pactus/transaction_pb2_grpc.py similarity index 100% rename from python/pactus/transaction_pb2_grpc.py rename to scripts/python/pactus/transaction_pb2_grpc.py diff --git a/python/pactus/wallet_pb2.py b/scripts/python/pactus/wallet_pb2.py similarity index 100% rename from python/pactus/wallet_pb2.py rename to scripts/python/pactus/wallet_pb2.py diff --git a/python/pactus/wallet_pb2_grpc.py b/scripts/python/pactus/wallet_pb2_grpc.py similarity index 100% rename from python/pactus/wallet_pb2_grpc.py rename to scripts/python/pactus/wallet_pb2_grpc.py diff --git a/python/public_key.py b/scripts/python/public_key.py similarity index 100% rename from python/public_key.py rename to scripts/python/public_key.py diff --git a/python/test.py b/scripts/python/test.py similarity index 100% rename from python/test.py rename to scripts/python/test.py diff --git a/python/utils.py b/scripts/python/utils.py similarity index 100% rename from python/utils.py rename to scripts/python/utils.py From a608b7e7dc3a6ab40a209c0ecf231cb96f6444a1 Mon Sep 17 00:00:00 2001 From: Kay Date: Fri, 22 Dec 2023 07:16:17 +0000 Subject: [PATCH 28/30] feat: adding check for same referral and user --- discord/discord.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/discord/discord.go b/discord/discord.go index 24007c1..334077c 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -239,6 +239,11 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) { return } + if referral.DiscordID == m.Author.ID { + _, _ = s.ChannelMessageSendReply(m.ChannelID, "Sorry, You can't be your own referral😔", m.Reference()) + return + } + if pubKey != "" { // check available balance balance := b.faucetWallet.GetBalance() From 77b910b71a4369fbdec5cd7b13439d20935a9f16 Mon Sep 17 00:00:00 2001 From: Kay Date: Wed, 27 Dec 2023 15:01:37 +0000 Subject: [PATCH 29/30] fix: mistakes in network detail command response --- discord/discord.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/discord/discord.go b/discord/discord.go index 334077c..0110930 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -441,10 +441,10 @@ func (b *Bot) networkInfo() string { return msg } msg += "\n📊 The current statistics are:\n" - msg += fmt.Sprintf("🕧Network started at: %v\n", time.UnixMilli(nodes.StartedAt*1000).Format("02/01/2006, 15:04:05")) + msg += fmt.Sprintf("Node started at: %v\n", time.UnixMilli(nodes.StartedAt*1000).Format("02/01/2006, 15:04:05")) msg += fmt.Sprintf("⬆️Total bytes sent: %v\n", uint32(nodes.TotalSentBytes)) msg += fmt.Sprintf("⬇️Total bytes received: %v\n", uint32(nodes.TotalReceivedBytes)) - msg += fmt.Sprintf("👾Number of peer nodes: %v\n", len(nodes.Peers)) + msg += fmt.Sprintf("👾Number of connected peers: %v\n", len(nodes.Peers)) // check block height blockchainInfo, err := b.cm.GetBlockchainInfo() if err != nil { From 8d7f79816133cc757607c18652ee2419aac666d3 Mon Sep 17 00:00:00 2001 From: Kay Date: Wed, 27 Dec 2023 15:04:16 +0000 Subject: [PATCH 30/30] fix: mistakes in network detail command response --- discord/discord.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/discord/discord.go b/discord/discord.go index 0110930..fc5d5dd 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -441,7 +441,7 @@ func (b *Bot) networkInfo() string { return msg } msg += "\n📊 The current statistics are:\n" - msg += fmt.Sprintf("Node started at: %v\n", time.UnixMilli(nodes.StartedAt*1000).Format("02/01/2006, 15:04:05")) + msg += fmt.Sprintf("🕧Node started at: %v\n", time.UnixMilli(nodes.StartedAt*1000).Format("02/01/2006, 15:04:05")) msg += fmt.Sprintf("⬆️Total bytes sent: %v\n", uint32(nodes.TotalSentBytes)) msg += fmt.Sprintf("⬇️Total bytes received: %v\n", uint32(nodes.TotalReceivedBytes)) msg += fmt.Sprintf("👾Number of connected peers: %v\n", len(nodes.Peers))