Commit 86bfe6d5 authored by Alexey's avatar Alexey Committed by Vlad Gaydukov
Browse files

Cosmos/rollup digest

parent a7e2410e
Showing with 4401 additions and 0 deletions
+4401 -0
target/
Cargo.lock
.vscode
\ No newline at end of file
# avvy-l2
- node - узел блокчейна реализованный на Cosmos SDK
## Node
Установить [Starport](https://github.com/tendermint/starport).
Добавить типы:
```
starport scaffold list rollup prev_hash current_hash ds_uri inbox
starport scaffold list message status name data
starport scaffold list l3node public_key options
starport scaffold map attachedUser userName:string --index iidap_id:int,account:int
starport scaffold list rollupDigest ds_uri:string current_hash:string status:string
```
## Использование
```
startport chain serve
```
Блокчейн API http://159.223.19.171:1317
Tendermint node: http://159.223.19.171:26657
Token faucet: http://159.223.19.171:4500
## Структуры
message L2Node {
string public_key;
repeated string options;
}
message Message {
uint64 status;
string name;
repeated string data;
}
message Rollup {
string prev_hash;
string current_hash;
string ds_uri;
repeated string inbox
}
## Запуск сервиса
```
starport chain serve
```
### Configure
Your blockchain in development can be configured with `config.yml`. To learn more, see the [Starport docs](https://docs.starport.network).
### Launch
To launch your blockchain live on multiple nodes, use `starport network` commands. Learn more about [Starport Network](https://github.com/tendermint/spn).
### Install
To install the latest version of your blockchain node's binary, execute the following command on your machine:
```
curl https://get.starport.network/cosmonaut/voter@latest! | sudo bash
```
`cosmonaut/voter` should match the `username` and `repo_name` of the Github repository to which the source code was pushed. Learn more about [the install process](https://github.com/allinbits/starport-installer).
main
goapp
\ No newline at end of file
# Cosmos Go
## Run
```bash
go run main.go
```
### Sequence
```bash
http://0.0.0.0:1317/auth/accounts/$USERADDRESS
```
## Users
### Alice
- address "cosmos15tp4859d4cf80k9z8fqycgsh9d9jc278gl6ra2" with
- mnemonic: "attend canoe twenty shallow beyond permit purpose eyebrow collect bunker hotel already garment globe wrong sunset hair cycle economy unlock ride magic grocery alien"
### Bob
- address "cosmos1rmtyahxknmle8dxyt9zxauzhpmmex7h698yaf9" with
- mnemonic: "sight quit diary ladder elbow crew inflict farm confirm mad ring entry because actor outside warrior hole can release asthma pride cloud ostrich joy"
The route guide server and client demonstrate how to use grpc go libraries to
perform unary, client streaming, server streaming and full duplex RPCs.
Please refer to [gRPC Basics: Go](https://grpc.io/docs/tutorials/basic/go.html) for more information.
See the definition of the route guide service in routeguide/route_guide.proto.
# Run the sample code
To compile and run the server, assuming you are in the root of the route_guide
folder, i.e., .../examples/route_guide/, simply:
```sh
$ go run server/server.go
```
Likewise, to run the client:
```sh
$ go run client/client.go
```
# Optional command line flags
The server and client both take optional command line flags. For example, the
client and server run without TLS by default. To enable TLS:
```sh
$ go run server/server.go -tls=true
```
and
```sh
$ go run client/client.go -tls=true
```
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries
// to perform unary, client streaming, server streaming and full duplex RPCs.
//
// It interacts with the route guide service whose definition can be found in routeguide/route_guide.proto.
package main
import (
"context"
"flag"
"log"
"time"
pb "../proto/gitlab.domi.do/avvy/avvy-l2/goapp/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/examples/data"
)
var (
tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
caFile = flag.String("ca_file", "", "The file containing the CA root cert file")
serverAddr = flag.String("addr", "localhost:50051", "The server address in the format of host:port")
serverHostOverride = flag.String("server_host_override", "x.test.example.com", "The server name used to verify the hostname returned by the TLS handshake")
)
func registerL3Node(client pb.L2Client, l3node *pb.MsgCreateL3Node) {
log.Printf("Create L3Node with: ", l3node.publicKey, l3node.options)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
feature, err := client.MsgCreateL3Node(ctx, l3node)
if err != nil {
log.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err)
}
log.Println(feature)
}
func main() {
flag.Parse()
var opts []grpc.DialOption
if *tls {
if *caFile == "" {
*caFile = data.Path("x509/ca_cert.pem")
}
creds, err := credentials.NewClientTLSFromFile(*caFile, *serverHostOverride)
if err != nil {
log.Fatalf("Failed to create TLS credentials %v", err)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithInsecure())
}
conn, err := grpc.Dial(*serverAddr, opts...)
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewL2Client(conn)
// Looking for a valid feature
registerL3Node(client, &pb.MsgCreateL3Node{creator: "409146138", publicKey: "746188906", options: "options"})
}
module github.com/cosmonaut/goapp
go 1.17
require (
filippo.io/edwards25519 v1.0.0-beta.2 // indirect
github.com/99designs/keyring v1.1.6 // indirect
github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect
github.com/DataDog/zstd v1.4.5 // indirect
github.com/armon/go-metrics v0.3.9 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/speakeasy v0.1.0 // indirect
github.com/btcsuite/btcd v0.22.0-beta // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/confio/ics23/go v0.6.6 // indirect
github.com/cosmonaut/voter v0.0.0 // indirect
github.com/cosmos/btcutil v1.0.4 // indirect
github.com/cosmos/cosmos-sdk v0.44.5 // indirect
github.com/cosmos/go-bip39 v1.0.0 // indirect
github.com/cosmos/iavl v0.17.3 // indirect
github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect
github.com/cosmos/ledger-go v0.9.2 // indirect
github.com/danieljoos/wincred v1.0.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgraph-io/badger/v2 v2.2007.2 // indirect
github.com/dgraph-io/ristretto v0.0.3 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect
github.com/enigmampc/btcutil v1.0.3-0.20200723161021-e2fb6adb2a25 // indirect
github.com/felixge/httpsnoop v1.0.1 // indirect
github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/go-kit/kit v0.10.0 // indirect
github.com/go-logfmt/logfmt v0.5.0 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gogo/gateway v1.1.0 // indirect
github.com/gogo/protobuf v1.3.3 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.3-0.20201103224600-674baa8c7fc3 // indirect
github.com/google/btree v1.0.0 // indirect
github.com/gorilla/handlers v1.5.1 // indirect
github.com/gorilla/mux v1.8.0 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
github.com/gtank/merlin v0.1.1 // indirect
github.com/gtank/ristretto255 v0.1.2 // indirect
github.com/hashicorp/go-immutable-radix v1.0.0 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d // indirect
github.com/libp2p/go-buffer-pool v0.0.2 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.4.1 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/pelletier/go-toml v1.9.3 // indirect
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.11.0 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.29.0 // indirect
github.com/prometheus/procfs v0.6.0 // indirect
github.com/rakyll/statik v0.1.7 // indirect
github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect
github.com/regen-network/cosmos-proto v0.3.1 // indirect
github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa // indirect
github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/spf13/cobra v1.2.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.8.1 // indirect
github.com/stretchr/testify v1.7.0 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca // indirect
github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c // indirect
github.com/tendermint/btcd v0.1.1 // indirect
github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tendermint/tendermint v0.34.14 // indirect
github.com/tendermint/tm-db v0.6.4 // indirect
github.com/zondax/hid v0.9.0 // indirect
go.etcd.io/bbolt v1.3.5 // indirect
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect
golang.org/x/net v0.0.0-20210903162142-ad29c8ab022f // indirect
golang.org/x/sys v0.0.0-20210903071746-97244b99971b // indirect
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
golang.org/x/text v0.3.6 // indirect
google.golang.org/genproto v0.0.0-20211129164237-f09f9a12af12 // indirect
google.golang.org/grpc v1.42.0 // indirect
google.golang.org/grpc/examples v0.0.0-20211209082858-fd4e3bdc3ac7 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
replace (
github.com/cosmonaut/voter v0.0.0 => ../node
github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1
google.golang.org/grpc => google.golang.org/grpc v1.33.2
)
This diff is collapsed.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"github.com/cosmos/cosmos-sdk/crypto/hd"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
xauthsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
// "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
typestx "github.com/cosmos/cosmos-sdk/types/tx"
avvytypes "github.com/cosmonaut/voter/x/voter/types"
"google.golang.org/grpc"
)
type Seq struct {
Height string `json:"height"`
Result SeqResult `json:"result"`
}
type SeqResult struct {
Type string `json:"type"`
Value SeqResultBody `json:"value"`
}
type SeqResultBody struct {
Address string `json:"address"`
Public_key SeqResultBodyPub `json:"public_key"`
Sequence string `json:"sequence"`
}
type SeqResultBodyPub struct {
Type string `json:"type"`
Value string `json:"value"`
}
func registerL3Node(l3_priv cryptotypes.PrivKey, l3node_pub cryptotypes.PubKey, l3_address sdk.AccAddress, options []string) error {
fmt.Println("L3 Node address: ", l3_address.String())
// TODO: нужно использовать app.AppCodec из cosmosapp
encCfg := simapp.MakeTestEncodingConfig()
// TODO забирать Passphrase из внешнего источника
const (
DefaultBIP39Passphrase = "attend canoe twenty shallow beyond permit purpose eyebrow collect bunker hotel already garment globe wrong sunset hair cycle economy unlock ride magic grocery alien"
)
// Создаём закрытый ключ Валидатора
hdPath := hd.CreateHDPath(118, 0, 0).String()
derivedPriv, errKeyDerive := hd.Secp256k1.Derive()(DefaultBIP39Passphrase, "", hdPath)
if errKeyDerive != nil {
println("errKeyDerive", errKeyDerive)
}
valPrivKey := hd.Secp256k1.Generate()(derivedPriv)
valAddress := sdk.AccAddress(valPrivKey.PubKey().Address())
creator := valAddress.String()
fmt.Println("Validator address: ", creator)
txBuilder := encCfg.TxConfig.NewTxBuilder()
msg1 := avvytypes.NewMsgCreateL3Node(creator, l3node_pub.String(), options)
errBult := txBuilder.SetMsgs(msg1)
if errBult != nil {
fmt.Println("txBuilder SetMsg ERROR: ", errBult)
return errBult
}
// TODO: определить тип монеты, в которых рассчитывается комиссия
var feeAmount = sdk.Coins{sdk.NewInt64Coin("foocoin", 0)}
// TODO: найти метод для GasEstimate
txBuilder.SetGasLimit(100000)
txBuilder.SetFeeAmount(feeAmount)
txBuilder.SetMemo("")
// TODO: получить текущую высоту блока
txBuilder.SetTimeoutHeight(73000)
privs := []cryptotypes.PrivKey{valPrivKey}
accNums := []uint64{0} // The accounts' account numbers
senderSeq := getSequence(valAddress)
number, errParse := strconv.ParseUint(string(senderSeq), 10, 64)
if errParse != nil {
fmt.Println("txBuilder SetMsg ERROR: ", errBult)
return errParse
}
accSeqs := []uint64{number} // The accounts' sequence numbers
// First round: we gather all the signer infos. We use the "set empty
// signature" hack to do that.
var sigsV2 []signing.SignatureV2
for i, priv := range privs {
sigV2 := signing.SignatureV2{
PubKey: priv.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: encCfg.TxConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
Sequence: accSeqs[i],
}
sigsV2 = append(sigsV2, sigV2)
}
res := txBuilder.SetSignatures(sigsV2...)
fmt.Println("esimated gas used:", res) // Prints estimated gas used.
// Second round: all signer infos are set, so each signer can sign.
var chainID = "voter"
sigsV2 = []signing.SignatureV2{}
for i, priv := range privs {
signerData := xauthsigning.SignerData{
ChainID: chainID,
AccountNumber: accNums[i],
Sequence: accSeqs[i],
}
sigV2, errSignWithPK := tx.SignWithPrivKey(
encCfg.TxConfig.SignModeHandler().DefaultMode(), signerData,
txBuilder, priv, encCfg.TxConfig, accSeqs[i])
if errSignWithPK != nil {
fmt.Println("tx SignWithPrivKey ERROR: ", errSignWithPK)
return errSignWithPK
}
sigsV2 = append(sigsV2, sigV2)
}
errSetSign := txBuilder.SetSignatures(sigsV2...)
if errSetSign != nil {
fmt.Println("txBuilder SetSignatures ERROR: ", errSetSign)
return errSetSign
}
txBytes, errTxEncoder := encCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
if errTxEncoder != nil {
fmt.Println("encCfg TxConfig TxEncoder ERROR: ", errTxEncoder)
return errTxEncoder
}
// // Generate a JSON string.
// txJSONBytes, err := encCfg.TxConfig.TxJSONEncoder()(txBuilder.GetTx())
// if err != nil {
// fmt.Println("encCfg TxConfig TxJSONEncoder ERROR: ", err)
// return err
// }
// txJSON := string(txJSONBytes)
// fmt.Println(txJSON)
// Create a connection to the gRPC server.
grpcConn, _ := grpc.Dial(
"127.0.0.1:9090", // Or your gRPC server address.
grpc.WithInsecure(), // The Cosmos SDK doesn't support any transport security mechanism.
)
defer grpcConn.Close()
// Broadcast the tx via gRPC. We create a new client for the Protobuf Tx
// service.
txClient := typestx.NewServiceClient(grpcConn)
// We then call the BroadcastTx method on this client.
grpcRes, errBroadcastTx := txClient.BroadcastTx(
context.Background(),
&typestx.BroadcastTxRequest{
Mode: typestx.BroadcastMode_BROADCAST_MODE_SYNC,
TxBytes: txBytes, // Proto-binary of the signed transaction, see previous step.
},
)
if errBroadcastTx != nil {
fmt.Println("txClient BroadcastTx ERROR: ", errBroadcastTx)
return errBroadcastTx
}
fmt.Println("grpcRes.TxResponse: ", grpcRes.TxResponse)
return nil
}
func registerRollup(prev_hash string, current_hash string, data_source_uri string, txs []string) error {
// TODO: нужно использовать app.AppCodec из cosmosapp
encCfg := simapp.MakeTestEncodingConfig()
// TODO забирать Passphrase из внешнего источника
const (
DefaultBIP39Passphrase = "attend canoe twenty shallow beyond permit purpose eyebrow collect bunker hotel already garment globe wrong sunset hair cycle economy unlock ride magic grocery alien"
)
// Создаём закрытый ключ Валидатора
hdPath := hd.CreateHDPath(118, 0, 0).String()
derivedPriv, errKeyDerive := hd.Secp256k1.Derive()(DefaultBIP39Passphrase, "", hdPath)
if errKeyDerive != nil {
println("errKeyDerive", errKeyDerive)
}
valPrivKey := hd.Secp256k1.Generate()(derivedPriv)
valAddress := sdk.AccAddress(valPrivKey.PubKey().Address())
creator := valAddress.String()
txBuilder := encCfg.TxConfig.NewTxBuilder()
msg1 := avvytypes.NewMsgCreateRollup(creator, prev_hash, current_hash, data_source_uri, txs)
errBult := txBuilder.SetMsgs(msg1)
if errBult != nil {
fmt.Println("txBuilder SetMsg ERROR: ", errBult)
return errBult
}
// TODO: определить тип монеты, в которых рассчитывается комиссия
var feeAmount = sdk.Coins{sdk.NewInt64Coin("foocoin", 0)}
// TODO: найти метод для GasEstimate
txBuilder.SetGasLimit(100000)
txBuilder.SetFeeAmount(feeAmount)
txBuilder.SetMemo("")
// TODO: получить текущую высоту блока
txBuilder.SetTimeoutHeight(73000)
privs := []cryptotypes.PrivKey{valPrivKey}
accNums := []uint64{0} // The accounts' account numbers
senderSeq := getSequence(valAddress)
number, errParse := strconv.ParseUint(string(senderSeq), 10, 64)
if errParse != nil {
fmt.Println("txBuilder SetMsg ERROR: ", errBult)
return errParse
}
accSeqs := []uint64{number} // The accounts' sequence numbers
// First round: we gather all the signer infos. We use the "set empty
// signature" hack to do that.
var sigsV2 []signing.SignatureV2
for i, priv := range privs {
sigV2 := signing.SignatureV2{
PubKey: priv.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: encCfg.TxConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
Sequence: accSeqs[i],
}
sigsV2 = append(sigsV2, sigV2)
}
res := txBuilder.SetSignatures(sigsV2...)
fmt.Println("esimated gas used:", res) // Prints estimated gas used.
// Second round: all signer infos are set, so each signer can sign.
var chainID = "voter"
sigsV2 = []signing.SignatureV2{}
for i, priv := range privs {
signerData := xauthsigning.SignerData{
ChainID: chainID,
AccountNumber: accNums[i],
Sequence: accSeqs[i],
}
sigV2, errSignWithPK := tx.SignWithPrivKey(
encCfg.TxConfig.SignModeHandler().DefaultMode(), signerData,
txBuilder, priv, encCfg.TxConfig, accSeqs[i])
if errSignWithPK != nil {
fmt.Println("tx SignWithPrivKey ERROR: ", errSignWithPK)
return errSignWithPK
}
sigsV2 = append(sigsV2, sigV2)
}
errSetSign := txBuilder.SetSignatures(sigsV2...)
if errSetSign != nil {
fmt.Println("txBuilder SetSignatures ERROR: ", errSetSign)
return errSetSign
}
txBytes, errTxEncoder := encCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
if errTxEncoder != nil {
fmt.Println("encCfg TxConfig TxEncoder ERROR: ", errTxEncoder)
return errTxEncoder
}
// // Generate a JSON string.
// txJSONBytes, err := encCfg.TxConfig.TxJSONEncoder()(txBuilder.GetTx())
// if err != nil {
// fmt.Println("encCfg TxConfig TxJSONEncoder ERROR: ", err)
// return err
// }
// txJSON := string(txJSONBytes)
// fmt.Println(txJSON)
// Create a connection to the gRPC server.
grpcConn, _ := grpc.Dial(
"0.0.0.0:9090", // Or your gRPC server address.
grpc.WithInsecure(), // The Cosmos SDK doesn't support any transport security mechanism.
)
defer grpcConn.Close()
// Broadcast the tx via gRPC. We create a new client for the Protobuf Tx
// service.
txClient := typestx.NewServiceClient(grpcConn)
// We then call the BroadcastTx method on this client.
grpcRes, errBroadcastTx := txClient.BroadcastTx(
context.Background(),
&typestx.BroadcastTxRequest{
Mode: typestx.BroadcastMode_BROADCAST_MODE_SYNC,
TxBytes: txBytes, // Proto-binary of the signed transaction, see previous step.
},
)
if errBroadcastTx != nil {
fmt.Println("txClient BroadcastTx ERROR: ", errBroadcastTx)
return errBroadcastTx
}
fmt.Println("grpcRes.TxResponse: ", grpcRes.TxResponse)
return nil
}
func faucet(addr sdk.AccAddress) {
values := map[string]string{"address": addr.String(), "coins": "100foocoin"}
json_data, err := json.Marshal(values)
resp, err := http.Post("http://0.0.0.0:4500/", "application/json", bytes.NewBuffer(json_data))
if err != nil {
log.Fatal(err)
}
fmt.Println("resp: ", resp)
}
func getSequence(addr sdk.AccAddress) string {
builder := strings.Builder{}
builder.WriteString("http://0.0.0.0:1317/auth/accounts/")
builder.WriteString(addr.String())
fmt.Println(builder.String())
resp, err := http.Get(builder.String())
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
textBytes := []byte(body)
seq1 := Seq{}
errUnmarshal := json.Unmarshal(textBytes, &seq1)
if errUnmarshal != nil {
fmt.Println(errUnmarshal)
}
fmt.Println("seq1: ", seq1)
return seq1.Result.Value.Sequence
}
func main() {
fmt.Println("\nStart\n")
privKey1, pubKey1, addr1 := testdata.KeyTestPubAddr()
registerL3Node(privKey1, pubKey1, addr1, []string{"options1", "options2"})
registerRollup("prev_hash", "current_hash", "dsu", []string{"tx1", "tx2", "tx3"})
fmt.Println("End")
}
syntax = "proto3";
option go_package = "gitlab.domi.do/avvy/avvy-l2/goapp/proto";
package l3;
service L3Service {
rpc ProcessTxn(TxnRequest) returns (TxnResponse) {}
}
message TxnRequest {
TxnRequestBody body = 1;
AuthInfo auth_info = 2;
}
message TxnRequestBody {
int64 txn_id = 1;
repeated Msg requests = 2;
}
message Msg {
uint64 id = 1;
map<string, bytes> body = 3; // вся инфа здесь
}
message AuthInfo {
repeated Signer signers = 1;
repeated Signature signatures = 2;
}
message Signer {
bytes public_key = 1;
uint64 nonce = 2; // покамест всегда 0, пока нет системы учета этого
}
message Signature {
bytes data = 1;
}
message TxnResponse {
TxnResponseBody body = 1;
AuthInfo auth_info = 2;
}
message TxnResponseBody {
int64 txn_id = 1;
repeated MsgResponse responses = 2;
}
message MsgResponse {
uint64 msg_id = 1;
enum Status {
ACCEPTED = 0;
DECLINED = 1;
REDIRECT = 2;
}
Status status = 2;
map<string, bytes> body = 3;
}
message Event {
Signer initiator = 1;
Msg msg = 2;
}
syntax = "proto3";
package tx;
option go_package = "gitlab.domi.do/avvy/avvy-l2/goapp/proto";
// Msg defines the Msg service.
service Msg {
rpc CreateL3Node(MsgCreateL3Node) returns (MsgCreateL3NodeResponse);
rpc UpdateL3Node(MsgUpdateL3Node) returns (MsgUpdateL3NodeResponse);
rpc DeleteL3Node(MsgDeleteL3Node) returns (MsgDeleteL3NodeResponse);
// this line is used by starport scaffolding # proto/tx/rpc
}
message MsgCreateL3Node {
string creator = 1;
string publicKey = 2;
repeated string options = 3;
}
message MsgCreateL3NodeResponse {
uint64 id = 1;
}
message MsgUpdateL3Node {
string creator = 1;
uint64 id = 2;
string publicKey = 3;
repeated string options = 4;
}
message MsgUpdateL3NodeResponse {}
message MsgDeleteL3Node {
string creator = 1;
uint64 id = 2;
}
message MsgDeleteL3NodeResponse {}
// this line is used by starport scaffolding # proto/tx/message
\ No newline at end of file
{
"height": "28355",
"result": {
"type": "cosmos-sdk/BaseAccount",
"value": {
"address": "cosmos15tp4859d4cf80k9z8fqycgsh9d9jc278gl6ra2",
"public_key": {
"type": "tendermint/PubKeySecp256k1",
"value": "A9fraWHv/nJM4iKZjWc75o3HjMtynpZ/JJx46zwbJryK"
},
"sequence": "7"
}
}
}
\ No newline at end of file
This diff is collapsed.
[{
"location": {
"latitude": 407838351,
"longitude": -746143763
},
"name": "Patriots Path, Mendham, NJ 07945, USA"
}, {
"location": {
"latitude": 408122808,
"longitude": -743999179
},
"name": "101 New Jersey 10, Whippany, NJ 07981, USA"
}, {
"location": {
"latitude": 413628156,
"longitude": -749015468
},
"name": "U.S. 6, Shohola, PA 18458, USA"
}, {
"location": {
"latitude": 419999544,
"longitude": -740371136
},
"name": "5 Conners Road, Kingston, NY 12401, USA"
}, {
"location": {
"latitude": 414008389,
"longitude": -743951297
},
"name": "Mid Hudson Psychiatric Center, New Hampton, NY 10958, USA"
}, {
"location": {
"latitude": 419611318,
"longitude": -746524769
},
"name": "287 Flugertown Road, Livingston Manor, NY 12758, USA"
}, {
"location": {
"latitude": 406109563,
"longitude": -742186778
},
"name": "4001 Tremley Point Road, Linden, NJ 07036, USA"
}, {
"location": {
"latitude": 416802456,
"longitude": -742370183
},
"name": "352 South Mountain Road, Wallkill, NY 12589, USA"
}, {
"location": {
"latitude": 412950425,
"longitude": -741077389
},
"name": "Bailey Turn Road, Harriman, NY 10926, USA"
}, {
"location": {
"latitude": 412144655,
"longitude": -743949739
},
"name": "193-199 Wawayanda Road, Hewitt, NJ 07421, USA"
}, {
"location": {
"latitude": 415736605,
"longitude": -742847522
},
"name": "406-496 Ward Avenue, Pine Bush, NY 12566, USA"
}, {
"location": {
"latitude": 413843930,
"longitude": -740501726
},
"name": "162 Merrill Road, Highland Mills, NY 10930, USA"
}, {
"location": {
"latitude": 410873075,
"longitude": -744459023
},
"name": "Clinton Road, West Milford, NJ 07480, USA"
}, {
"location": {
"latitude": 412346009,
"longitude": -744026814
},
"name": "16 Old Brook Lane, Warwick, NY 10990, USA"
}, {
"location": {
"latitude": 402948455,
"longitude": -747903913
},
"name": "3 Drake Lane, Pennington, NJ 08534, USA"
}, {
"location": {
"latitude": 406337092,
"longitude": -740122226
},
"name": "6324 8th Avenue, Brooklyn, NY 11220, USA"
}, {
"location": {
"latitude": 406421967,
"longitude": -747727624
},
"name": "1 Merck Access Road, Whitehouse Station, NJ 08889, USA"
}, {
"location": {
"latitude": 416318082,
"longitude": -749677716
},
"name": "78-98 Schalck Road, Narrowsburg, NY 12764, USA"
}, {
"location": {
"latitude": 415301720,
"longitude": -748416257
},
"name": "282 Lakeview Drive Road, Highland Lake, NY 12743, USA"
}, {
"location": {
"latitude": 402647019,
"longitude": -747071791
},
"name": "330 Evelyn Avenue, Hamilton Township, NJ 08619, USA"
}, {
"location": {
"latitude": 412567807,
"longitude": -741058078
},
"name": "New York State Reference Route 987E, Southfields, NY 10975, USA"
}, {
"location": {
"latitude": 416855156,
"longitude": -744420597
},
"name": "103-271 Tempaloni Road, Ellenville, NY 12428, USA"
}, {
"location": {
"latitude": 404663628,
"longitude": -744820157
},
"name": "1300 Airport Road, North Brunswick Township, NJ 08902, USA"
}, {
"location": {
"latitude": 407113723,
"longitude": -749746483
},
"name": ""
}, {
"location": {
"latitude": 402133926,
"longitude": -743613249
},
"name": ""
}, {
"location": {
"latitude": 400273442,
"longitude": -741220915
},
"name": ""
}, {
"location": {
"latitude": 411236786,
"longitude": -744070769
},
"name": ""
}, {
"location": {
"latitude": 411633782,
"longitude": -746784970
},
"name": "211-225 Plains Road, Augusta, NJ 07822, USA"
}, {
"location": {
"latitude": 415830701,
"longitude": -742952812
},
"name": ""
}, {
"location": {
"latitude": 413447164,
"longitude": -748712898
},
"name": "165 Pedersen Ridge Road, Milford, PA 18337, USA"
}, {
"location": {
"latitude": 405047245,
"longitude": -749800722
},
"name": "100-122 Locktown Road, Frenchtown, NJ 08825, USA"
}, {
"location": {
"latitude": 418858923,
"longitude": -746156790
},
"name": ""
}, {
"location": {
"latitude": 417951888,
"longitude": -748484944
},
"name": "650-652 Willi Hill Road, Swan Lake, NY 12783, USA"
}, {
"location": {
"latitude": 407033786,
"longitude": -743977337
},
"name": "26 East 3rd Street, New Providence, NJ 07974, USA"
}, {
"location": {
"latitude": 417548014,
"longitude": -740075041
},
"name": ""
}, {
"location": {
"latitude": 410395868,
"longitude": -744972325
},
"name": ""
}, {
"location": {
"latitude": 404615353,
"longitude": -745129803
},
"name": ""
}, {
"location": {
"latitude": 406589790,
"longitude": -743560121
},
"name": "611 Lawrence Avenue, Westfield, NJ 07090, USA"
}, {
"location": {
"latitude": 414653148,
"longitude": -740477477
},
"name": "18 Lannis Avenue, New Windsor, NY 12553, USA"
}, {
"location": {
"latitude": 405957808,
"longitude": -743255336
},
"name": "82-104 Amherst Avenue, Colonia, NJ 07067, USA"
}, {
"location": {
"latitude": 411733589,
"longitude": -741648093
},
"name": "170 Seven Lakes Drive, Sloatsburg, NY 10974, USA"
}, {
"location": {
"latitude": 412676291,
"longitude": -742606606
},
"name": "1270 Lakes Road, Monroe, NY 10950, USA"
}, {
"location": {
"latitude": 409224445,
"longitude": -748286738
},
"name": "509-535 Alphano Road, Great Meadows, NJ 07838, USA"
}, {
"location": {
"latitude": 406523420,
"longitude": -742135517
},
"name": "652 Garden Street, Elizabeth, NJ 07202, USA"
}, {
"location": {
"latitude": 401827388,
"longitude": -740294537
},
"name": "349 Sea Spray Court, Neptune City, NJ 07753, USA"
}, {
"location": {
"latitude": 410564152,
"longitude": -743685054
},
"name": "13-17 Stanley Street, West Milford, NJ 07480, USA"
}, {
"location": {
"latitude": 408472324,
"longitude": -740726046
},
"name": "47 Industrial Avenue, Teterboro, NJ 07608, USA"
}, {
"location": {
"latitude": 412452168,
"longitude": -740214052
},
"name": "5 White Oak Lane, Stony Point, NY 10980, USA"
}, {
"location": {
"latitude": 409146138,
"longitude": -746188906
},
"name": "Berkshire Valley Management Area Trail, Jefferson, NJ, USA"
}, {
"location": {
"latitude": 404701380,
"longitude": -744781745
},
"name": "1007 Jersey Avenue, New Brunswick, NJ 08901, USA"
}, {
"location": {
"latitude": 409642566,
"longitude": -746017679
},
"name": "6 East Emerald Isle Drive, Lake Hopatcong, NJ 07849, USA"
}, {
"location": {
"latitude": 408031728,
"longitude": -748645385
},
"name": "1358-1474 New Jersey 57, Port Murray, NJ 07865, USA"
}, {
"location": {
"latitude": 413700272,
"longitude": -742135189
},
"name": "367 Prospect Road, Chester, NY 10918, USA"
}, {
"location": {
"latitude": 404310607,
"longitude": -740282632
},
"name": "10 Simon Lake Drive, Atlantic Highlands, NJ 07716, USA"
}, {
"location": {
"latitude": 409319800,
"longitude": -746201391
},
"name": "11 Ward Street, Mount Arlington, NJ 07856, USA"
}, {
"location": {
"latitude": 406685311,
"longitude": -742108603
},
"name": "300-398 Jefferson Avenue, Elizabeth, NJ 07201, USA"
}, {
"location": {
"latitude": 419018117,
"longitude": -749142781
},
"name": "43 Dreher Road, Roscoe, NY 12776, USA"
}, {
"location": {
"latitude": 412856162,
"longitude": -745148837
},
"name": "Swan Street, Pine Island, NY 10969, USA"
}, {
"location": {
"latitude": 416560744,
"longitude": -746721964
},
"name": "66 Pleasantview Avenue, Monticello, NY 12701, USA"
}, {
"location": {
"latitude": 405314270,
"longitude": -749836354
},
"name": ""
}, {
"location": {
"latitude": 414219548,
"longitude": -743327440
},
"name": ""
}, {
"location": {
"latitude": 415534177,
"longitude": -742900616
},
"name": "565 Winding Hills Road, Montgomery, NY 12549, USA"
}, {
"location": {
"latitude": 406898530,
"longitude": -749127080
},
"name": "231 Rocky Run Road, Glen Gardner, NJ 08826, USA"
}, {
"location": {
"latitude": 407586880,
"longitude": -741670168
},
"name": "100 Mount Pleasant Avenue, Newark, NJ 07104, USA"
}, {
"location": {
"latitude": 400106455,
"longitude": -742870190
},
"name": "517-521 Huntington Drive, Manchester Township, NJ 08759, USA"
}, {
"location": {
"latitude": 400066188,
"longitude": -746793294
},
"name": ""
}, {
"location": {
"latitude": 418803880,
"longitude": -744102673
},
"name": "40 Mountain Road, Napanoch, NY 12458, USA"
}, {
"location": {
"latitude": 414204288,
"longitude": -747895140
},
"name": ""
}, {
"location": {
"latitude": 414777405,
"longitude": -740615601
},
"name": ""
}, {
"location": {
"latitude": 415464475,
"longitude": -747175374
},
"name": "48 North Road, Forestburgh, NY 12777, USA"
}, {
"location": {
"latitude": 404062378,
"longitude": -746376177
},
"name": ""
}, {
"location": {
"latitude": 405688272,
"longitude": -749285130
},
"name": ""
}, {
"location": {
"latitude": 400342070,
"longitude": -748788996
},
"name": ""
}, {
"location": {
"latitude": 401809022,
"longitude": -744157964
},
"name": ""
}, {
"location": {
"latitude": 404226644,
"longitude": -740517141
},
"name": "9 Thompson Avenue, Leonardo, NJ 07737, USA"
}, {
"location": {
"latitude": 410322033,
"longitude": -747871659
},
"name": ""
}, {
"location": {
"latitude": 407100674,
"longitude": -747742727
},
"name": ""
}, {
"location": {
"latitude": 418811433,
"longitude": -741718005
},
"name": "213 Bush Road, Stone Ridge, NY 12484, USA"
}, {
"location": {
"latitude": 415034302,
"longitude": -743850945
},
"name": ""
}, {
"location": {
"latitude": 411349992,
"longitude": -743694161
},
"name": ""
}, {
"location": {
"latitude": 404839914,
"longitude": -744759616
},
"name": "1-17 Bergen Court, New Brunswick, NJ 08901, USA"
}, {
"location": {
"latitude": 414638017,
"longitude": -745957854
},
"name": "35 Oakland Valley Road, Cuddebackville, NY 12729, USA"
}, {
"location": {
"latitude": 412127800,
"longitude": -740173578
},
"name": ""
}, {
"location": {
"latitude": 401263460,
"longitude": -747964303
},
"name": ""
}, {
"location": {
"latitude": 412843391,
"longitude": -749086026
},
"name": ""
}, {
"location": {
"latitude": 418512773,
"longitude": -743067823
},
"name": ""
}, {
"location": {
"latitude": 404318328,
"longitude": -740835638
},
"name": "42-102 Main Street, Belford, NJ 07718, USA"
}, {
"location": {
"latitude": 419020746,
"longitude": -741172328
},
"name": ""
}, {
"location": {
"latitude": 404080723,
"longitude": -746119569
},
"name": ""
}, {
"location": {
"latitude": 401012643,
"longitude": -744035134
},
"name": ""
}, {
"location": {
"latitude": 404306372,
"longitude": -741079661
},
"name": ""
}, {
"location": {
"latitude": 403966326,
"longitude": -748519297
},
"name": ""
}, {
"location": {
"latitude": 405002031,
"longitude": -748407866
},
"name": ""
}, {
"location": {
"latitude": 409532885,
"longitude": -742200683
},
"name": ""
}, {
"location": {
"latitude": 416851321,
"longitude": -742674555
},
"name": ""
}, {
"location": {
"latitude": 406411633,
"longitude": -741722051
},
"name": "3387 Richmond Terrace, Staten Island, NY 10303, USA"
}, {
"location": {
"latitude": 413069058,
"longitude": -744597778
},
"name": "261 Van Sickle Road, Goshen, NY 10924, USA"
}, {
"location": {
"latitude": 418465462,
"longitude": -746859398
},
"name": ""
}, {
"location": {
"latitude": 411733222,
"longitude": -744228360
},
"name": ""
}, {
"location": {
"latitude": 410248224,
"longitude": -747127767
},
"name": "3 Hasta Way, Newton, NJ 07860, USA"
}]
*/.idea*
*/pymerk/.env*
*/pymerk/target*
*/pymerk/pymerk*
*/pymerk/pymerk.egg-info*
*/pymerk/test.merkdb
*/*.cpython-36.pyc
*/*.DS_Store
*/*.coverage
*/*.pyc
*/*.so
*/*.o
*/*.c
*/*.pyd
*/*.exe
*/*.cbor
*/*.pickle
*/build
*/.idea*
*/*.cpython-36m-darwin.so
*/*.cbor.blosc
*/*.gitsecret/keys/random_seed
!*.secret
/*/__pycache__/*
/*/*/__pycache__/*
/*/*/*/__pycache__/*
/*/*/*/*/__pycache__/*
ipfs/compose
ipfs/temp
ipfs/.idea/*
*/*.pem
.env
\ No newline at end of file
# AvvyLayer 1
## Подготовка и запуск
```bash
python3.9 -m venv .env
source .env/bin/activate
pip install -r requirements
python src/send_tx.py
```
## Сделать Protobuf модели
<!-- python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. src/proto/l_3_node.proto
python -m grpc_tools.protoc -I./proto/voter --python_out=. --grpc_python_out=. rollup.proto -->
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. voter/*
## Запрость методы gRPC
grpcurl -plaintext localhost:9090 list
grpcurl -plaintext localhost:9090 describe cosmos.tx.v1beta1.Service
grpcurl -plaintext -d '{"address":"$MY_VALIDATOR"}' localhost:9090 cosmos.tx.v1beta1.Service
grpcurl -plaintext -d '{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' localhost:9090 cosmos.tx.v1beta1.Service/BroadcastTx
\ No newline at end of file
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# IntelliJ
.idea/
# A script that can be used for quick testing
tester.py
[![Build Status](https://github.com/hukkin/cosmospy/workflows/Tests/badge.svg?branch=master)](https://github.com/hukkin/cosmospy/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush)
[![codecov.io](https://codecov.io/gh/hukkin/cosmospy/branch/master/graph/badge.svg)](https://codecov.io/gh/hukkin/cosmospy)
[![PyPI version](https://img.shields.io/pypi/v/cosmospy)](https://pypi.org/project/cosmospy)
# cosmospy
<!--- Don't edit the version line below manually. Let bump2version do it for you. -->
> Version 6.0.0
> Tools for Cosmos wallet management and offline transaction signing
**Table of Contents** *generated with [mdformat-toc](https://github.com/hukkin/mdformat-toc)*
<!-- mdformat-toc start --slug=github --maxlevel=6 --minlevel=2 -->
- [Installing](#installing)
- [Usage](#usage)
- [Generating a wallet](#generating-a-wallet)
- [Converter functions](#converter-functions)
- [Mnemonic seed to private key](#mnemonic-seed-to-private-key)
- [Private key to public key](#private-key-to-public-key)
- [Public key to address](#public-key-to-address)
- [Private key to address](#private-key-to-address)
- [Signing transactions](#signing-transactions)
<!-- mdformat-toc end -->
## Installing<a name="installing"></a>
Installing from PyPI repository (https://pypi.org/project/cosmospy):
```bash
pip install cosmospy
```
## Usage<a name="usage"></a>
### Generating a wallet<a name="generating-a-wallet"></a>
```python
from cosmospy import generate_wallet
wallet = generate_wallet()
```
The value assigned to `wallet` will be a dictionary just like:
```python
{
"seed": "arch skill acquire abuse frown reject front second album pizza hill slogan guess random wonder benefit industry custom green ill moral daring glow elevator",
"derivation_path": "m/44'/118'/0'/0/0",
"private_key": b"\xbb\xec^\xf6\xdcg\xe6\xb5\x89\xed\x8cG\x05\x03\xdf0:\xc9\x8b \x85\x8a\x14\x12\xd7\xa6a\x01\xcd\xf8\x88\x93",
"public_key": b"\x03h\x1d\xae\xa7\x9eO\x8e\xc5\xff\xa3sAw\xe6\xdd\xc9\xb8b\x06\x0eo\xc5a%z\xe3\xff\x1e\xd2\x8e5\xe7",
"address": "cosmos1uuhna3psjqfxnw4msrfzsr0g08yuyfxeht0qfh",
}
```
### Converter functions<a name="converter-functions"></a>
#### Mnemonic seed to private key<a name="mnemonic-seed-to-private-key"></a>
```python
from cosmospy import BIP32DerivationError, seed_to_privkey
seed = (
"teach there dream chase fatigue abandon lava super senior artefact close upgrade"
)
try:
privkey = seed_to_privkey(seed, path="m/44'/118'/0'/0/0")
except BIP32DerivationError:
print("No valid private key in this derivation path!")
```
#### Private key to public key<a name="private-key-to-public-key"></a>
```python
from cosmospy import privkey_to_pubkey
privkey = bytes.fromhex(
"6dcd05d7ac71e09d3cf7da666709ebd59362486ff9e99db0e8bc663570515afa"
)
pubkey = privkey_to_pubkey(privkey)
```
#### Public key to address<a name="public-key-to-address"></a>
```python
from cosmospy import pubkey_to_address
pubkey = bytes.fromhex(
"03e8005aad74da5a053602f86e3151d4f3214937863a11299c960c28d3609c4775"
)
addr = pubkey_to_address(pubkey)
```
#### Private key to address<a name="private-key-to-address"></a>
```python
from cosmospy import privkey_to_address
privkey = bytes.fromhex(
"6dcd05d7ac71e09d3cf7da666709ebd59362486ff9e99db0e8bc663570515afa"
)
addr = privkey_to_address(privkey)
```
### Signing transactions<a name="signing-transactions"></a>
```python
from cosmospy import Transaction
tx = Transaction(
privkey=bytes.fromhex(
"26d167d549a4b2b66f766b0d3f2bdbe1cd92708818c338ff453abde316a2bd59"
),
account_num=11335,
sequence=0,
fee=1000,
gas=70000,
memo="",
chain_id="cosmoshub-4",
sync_mode="sync",
)
tx.add_transfer(
recipient="cosmos103l758ps7403sd9c0y8j6hrfw4xyl70j4mmwkf", amount=387000
)
tx.add_transfer(recipient="cosmos1lzumfk6xvwf9k9rk72mqtztv867xyem393um48", amount=123)
pushable_tx = tx.get_pushable()
# Optionally submit the transaction using your preferred method.
# This example uses the httpx library.
import httpx
api_base_url = "https://node.atomscan.com"
httpx.post(api_base_url + "/txs", data=pushable_tx)
```
One or more token transfers can be added to a transaction by calling the `add_transfer` method.
When the transaction is fully prepared, calling `get_pushable` will return a signed transaction in the form of a JSON string.
This can be used as request body when calling the `POST /txs` endpoint of the [Cosmos REST API](https://cosmos.network/rpc).
__version__ = "6.0.0" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
from hdwallets import BIP32DerivationError as BIP32DerivationError # noqa: F401
from cosmospy._transaction import Transaction as Transaction # noqa: F401
from cosmospy._wallet import generate_wallet as generate_wallet # noqa: F401
from cosmospy._wallet import privkey_to_address as privkey_to_address # noqa: F401
from cosmospy._wallet import privkey_to_pubkey as privkey_to_pubkey # noqa: F401
from cosmospy._wallet import pubkey_to_address as pubkey_to_address # noqa: F401
from cosmospy._wallet import seed_to_privkey as seed_to_privkey # noqa: F401
from __future__ import annotations
import base64
import hashlib
import json
from typing import Any
import ecdsa
from cosmospy._wallet import DEFAULT_BECH32_HRP, privkey_to_address, privkey_to_pubkey
from cosmospy.typing import SyncMode
class Transaction:
"""A Cosmos transaction.
After initialization, one or more token transfers can be added by
calling the `add_transfer()` method. Finally, call `get_pushable()`
to get a signed transaction that can be pushed to the `POST /txs`
endpoint of the Cosmos REST API.
"""
def __init__(
self,
*,
privkey: bytes,
account_num: int,
sequence: int,
fee: int,
gas: int,
fee_denom: str = "uatom",
memo: str = "",
chain_id: str = "cosmoshub-4",
hrp: str = DEFAULT_BECH32_HRP,
sync_mode: SyncMode = "sync",
) -> None:
self._privkey = privkey
self._account_num = account_num
self._sequence = sequence
self._fee = fee
self._fee_denom = fee_denom
self._gas = gas
self._memo = memo
self._chain_id = chain_id
self._hrp = hrp
self._sync_mode = sync_mode
self._msgs: list[dict] = []
def add_transfer(self, recipient: str, amount: int, denom: str = "uatom") -> None:
transfer = {
"type": "cosmos-sdk/MsgSend",
"value": {
"from_address": privkey_to_address(self._privkey, hrp=self._hrp),
"to_address": recipient,
"amount": [{"denom": denom, "amount": str(amount)}],
},
}
self._msgs.append(transfer)
def add_l3_node(self):
transfer = {
"type": "cosmonaut.voter.voter.MsgCreateL3Node",
"value": {
"creator": privkey_to_address(self._privkey, hrp=self._hrp),
"publicKey": "node_pubkey",
"options": ["nodeOptions"],
},
}
self._msgs.append(transfer)
def get_pushable(self) -> str:
pubkey = privkey_to_pubkey(self._privkey)
base64_pubkey = base64.b64encode(pubkey).decode("utf-8")
pushable_tx = {
"tx": {
"msg": self._msgs,
"fee": {
"gas": str(self._gas),
"amount": [{"denom": self._fee_denom, "amount": str(self._fee)}],
},
"memo": self._memo,
"signatures": [
{
"signature": self._sign(),
"pub_key": {"type": "tendermint/PubKeySecp256k1", "value": base64_pubkey},
"account_number": str(self._account_num),
"sequence": str(self._sequence),
}
],
},
"mode": self._sync_mode,
}
return json.dumps(pushable_tx, separators=(",", ":"))
def _sign(self) -> str:
message_str = json.dumps(self._get_sign_message(), separators=(",", ":"), sort_keys=True)
message_bytes = message_str.encode("utf-8")
privkey = ecdsa.SigningKey.from_string(self._privkey, curve=ecdsa.SECP256k1)
signature_compact = privkey.sign_deterministic(
message_bytes, hashfunc=hashlib.sha256, sigencode=ecdsa.util.sigencode_string_canonize
)
signature_base64_str = base64.b64encode(signature_compact).decode("utf-8")
return signature_base64_str
def _get_sign_message(self) -> dict[str, Any]:
return {
"chain_id": self._chain_id,
"account_number": str(self._account_num),
"fee": {
"gas": str(self._gas),
"amount": [{"amount": str(self._fee), "denom": self._fee_denom}],
},
"memo": self._memo,
"sequence": str(self._sequence),
"msgs": self._msgs,
}
import hashlib
import bech32
import ecdsa
import hdwallets
import mnemonic
from cosmospy import BIP32DerivationError
from cosmospy.typing import Wallet
DEFAULT_DERIVATION_PATH = "m/44'/118'/0'/0/0"
DEFAULT_BECH32_HRP = "cosmos"
def generate_wallet(
*, path: str = DEFAULT_DERIVATION_PATH, hrp: str = DEFAULT_BECH32_HRP
) -> Wallet:
while True:
phrase = mnemonic.Mnemonic(language="english").generate(strength=256)
try:
privkey = seed_to_privkey(phrase, path=path)
break
except BIP32DerivationError:
pass
pubkey = privkey_to_pubkey(privkey)
address = pubkey_to_address(pubkey, hrp=hrp)
return {
"seed": phrase,
"derivation_path": path,
"private_key": privkey,
"public_key": pubkey,
"address": address,
}
def seed_to_privkey(seed: str, path: str = DEFAULT_DERIVATION_PATH) -> bytes:
"""Get a private key from a mnemonic seed and a derivation path.
Assumes a BIP39 mnemonic seed with no passphrase. Raises
`cosmospy.BIP32DerivationError` if the resulting private key is
invalid.
"""
seed_bytes = mnemonic.Mnemonic.to_seed(seed, passphrase="")
hd_wallet = hdwallets.BIP32.from_seed(seed_bytes)
# This can raise a `hdwallets.BIP32DerivationError` (which we alias so
# that the same exception type is also in the `cosmospy` namespace).
derived_privkey = hd_wallet.get_privkey_from_path(path)
return derived_privkey
def privkey_to_pubkey(privkey: bytes) -> bytes:
privkey_obj = ecdsa.SigningKey.from_string(privkey, curve=ecdsa.SECP256k1)
pubkey_obj = privkey_obj.get_verifying_key()
return pubkey_obj.to_string("compressed")
def pubkey_to_address(pubkey: bytes, *, hrp: str = DEFAULT_BECH32_HRP) -> str:
s = hashlib.new("sha256", pubkey).digest()
r = hashlib.new("ripemd160", s).digest()
five_bit_r = bech32.convertbits(r, 8, 5)
assert five_bit_r is not None, "Unsuccessful bech32.convertbits call"
return bech32.bech32_encode(hrp, five_bit_r)
def privkey_to_address(privkey: bytes, *, hrp: str = DEFAULT_BECH32_HRP) -> str:
pubkey = privkey_to_pubkey(privkey)
return pubkey_to_address(pubkey, hrp=hrp)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment