migrate code and fix go mod

This commit is contained in:
Solovyov1796 2024-04-24 15:10:22 +08:00
parent 5207a300ad
commit dde7485ee9
175 changed files with 11447 additions and 658 deletions

View File

@ -1,8 +1,10 @@
################################################################################ ################################################################################
### Project Info ### ### Project Info ###
################################################################################ ################################################################################
PROJECT_NAME := kava# unique namespace for project PROJECT_NAME := 0g-chain# unique namespace for project
MAIN_ENTRY := ./cmd
BINARY_NAME := 0gchaind
DOCKER_IMAGE_NAME := 0glabs/0g-chain
GO_BIN ?= go GO_BIN ?= go
GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD) GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
@ -37,7 +39,7 @@ print-git-info:
.PHONY: print-version .PHONY: print-version
print-version: print-version:
@echo "kava $(VERSION)\ntendermint $(TENDERMINT_VERSION)\ncosmos $(COSMOS_SDK_VERSION)" @echo "$(BINARY_NAME) $(VERSION)\ntendermint $(TENDERMINT_VERSION)\ncosmos $(COSMOS_SDK_VERSION)"
################################################################################ ################################################################################
### Project Settings ### ### Project Settings ###
@ -45,7 +47,7 @@ print-version:
LEDGER_ENABLED ?= true LEDGER_ENABLED ?= true
DOCKER:=docker DOCKER:=docker
DOCKER_BUF := $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace bufbuild/buf DOCKER_BUF := $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace bufbuild/buf
HTTPS_GIT := https://github.com/Kava-Labs/kava.git HTTPS_GIT := https://github.com/0glabs/0g-chain.git
################################################################################ ################################################################################
### Machine Info ### ### Machine Info ###
@ -142,8 +144,8 @@ build_tags_comma_sep := $(subst $(whitespace),$(comma),$(build_tags))
# process linker flags # process linker flags
ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=kava \ ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=$(PROJECT_NAME) \
-X github.com/cosmos/cosmos-sdk/version.AppName=kava \ -X github.com/cosmos/cosmos-sdk/version.AppName=$(PROJECT_NAME) \
-X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION_NUMBER) \ -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION_NUMBER) \
-X github.com/cosmos/cosmos-sdk/version.Commit=$(GIT_COMMIT) \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(GIT_COMMIT) \
-X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" \ -X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" \
@ -188,15 +190,15 @@ all: install
build: go.sum build: go.sum
ifeq ($(OS), Windows_NT) ifeq ($(OS), Windows_NT)
$(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/kava.exe ./cmd/kava $(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/$(BINARY_NAME).exe $(MAIN_ENTRY)
else else
$(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/kava ./cmd/kava $(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/$(BINARY_NAME) $(MAIN_ENTRY)
endif endif
build-linux: go.sum build-linux: go.sum
LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build
# build on rocksdb-backed kava on macOS with shared libs from brew # build on rocksdb-backed 0gchaind on macOS with shared libs from brew
# this assumes you are on macOS & these deps have been installed with brew: # this assumes you are on macOS & these deps have been installed with brew:
# rocksdb, snappy, lz4, and zstd # rocksdb, snappy, lz4, and zstd
# use like `make build-rocksdb-brew COSMOS_BUILD_OPTIONS=rocksdb` # use like `make build-rocksdb-brew COSMOS_BUILD_OPTIONS=rocksdb`
@ -205,7 +207,7 @@ build-rocksdb-brew:
export CGO_LDFLAGS := -L$(shell brew --prefix rocksdb)/lib -lrocksdb -lstdc++ -lm -lz -L$(shell brew --prefix snappy)/lib -L$(shell brew --prefix lz4)/lib -L$(shell brew --prefix zstd)/lib export CGO_LDFLAGS := -L$(shell brew --prefix rocksdb)/lib -lrocksdb -lstdc++ -lm -lz -L$(shell brew --prefix snappy)/lib -L$(shell brew --prefix lz4)/lib -L$(shell brew --prefix zstd)/lib
install: go.sum install: go.sum
$(GO_BIN) install -mod=readonly $(BUILD_FLAGS) ./cmd/kava $(GO_BIN) install -mod=readonly $(BUILD_FLAGS) $(MAIN_ENTRY)
######################################## ########################################
### Tools & dependencies ### Tools & dependencies
@ -227,6 +229,7 @@ go.sum: go.mod
# Set to exclude riot links as they trigger false positives # Set to exclude riot links as they trigger false positives
link-check: link-check:
@$(GO_BIN) get -u github.com/raviqqe/liche@f57a5d1c5be4856454cb26de155a65a4fd856ee3 @$(GO_BIN) get -u github.com/raviqqe/liche@f57a5d1c5be4856454cb26de155a65a4fd856ee3
# TODO: replace kava in following line with project name
liche -r . --exclude "^http://127.*|^https://riot.im/app*|^http://kava-testnet*|^https://testnet-dex*|^https://kava3.data.kava.io*|^https://ipfs.io*|^https://apps.apple.com*|^https://kava.quicksync.io*" liche -r . --exclude "^http://127.*|^https://riot.im/app*|^http://kava-testnet*|^https://testnet-dex*|^https://kava3.data.kava.io*|^https://ipfs.io*|^https://apps.apple.com*|^https://kava.quicksync.io*"
@ -241,26 +244,26 @@ format:
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs misspell -w find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs misspell -w
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/tendermint find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/tendermint
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/cosmos/cosmos-sdk find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/cosmos/cosmos-sdk
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/kava-labs/kava find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/0glabs/0g-chain
.PHONY: format .PHONY: format
############################################################################### ###############################################################################
### Localnet ### ### Localnet ###
############################################################################### ###############################################################################
# Build docker image and tag as kava/kava:local # Build docker image and tag as 0glabs/0g-chain:local
docker-build: docker-build:
DOCKER_BUILDKIT=1 $(DOCKER) build -t kava/kava:local . DOCKER_BUILDKIT=1 $(DOCKER) build -t $(DOCKER_IMAGE_NAME):local .
docker-build-rocksdb: docker-build-rocksdb:
DOCKER_BUILDKIT=1 $(DOCKER) build -f Dockerfile-rocksdb -t kava/kava:local . DOCKER_BUILDKIT=1 $(DOCKER) build -f Dockerfile-rocksdb -t $(DOCKER_IMAGE_NAME):local .
build-docker-local-kava: build-docker-local-0gchain:
@$(MAKE) -C networks/local @$(MAKE) -C networks/local
# Run a 4-node testnet locally # Run a 4-node testnet locally
localnet-start: build-linux localnet-stop localnet-start: build-linux localnet-stop
@if ! [ -f build/node0/kvd/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/kvd:Z kava/kavanode testnet --v 4 -o . --starting-ip-address 192.168.10.2 --keyring-backend=test ; fi @if ! [ -f build/node0/kvd/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/kvd:Z $(DOCKER_IMAGE_NAME)-node testnet --v 4 -o . --starting-ip-address 192.168.10.2 --keyring-backend=test ; fi
docker-compose up -d docker-compose up -d
localnet-stop: localnet-stop:
@ -269,7 +272,7 @@ localnet-stop:
# Launch a new single validator chain # Launch a new single validator chain
start: start:
./contrib/devnet/init-new-chain.sh ./contrib/devnet/init-new-chain.sh
kava start $(BINARY_NAME) start
#proto-format: #proto-format:
#@echo "Formatting Protobuf files" #@echo "Formatting Protobuf files"
@ -310,7 +313,7 @@ test:
@$(GO_BIN) test $$($(GO_BIN) list ./... | grep -v 'contrib' | grep -v 'tests/e2e') @$(GO_BIN) test $$($(GO_BIN) list ./... | grep -v 'contrib' | grep -v 'tests/e2e')
test-rocksdb: test-rocksdb:
@go test -tags=rocksdb ./cmd/kava/opendb @go test -tags=rocksdb $(MAIN_ENTRY)/opendb
# Run cli integration tests # Run cli integration tests
# `-p 4` to use 4 cores, `-tags cli_test` to tell $(GO_BIN) not to ignore the cli package # `-p 4` to use 4 cores, `-tags cli_test` to tell $(GO_BIN) not to ignore the cli package
@ -326,15 +329,15 @@ test-migrate:
# This submits an AWS Batch job to run a lot of sims, each within a docker image. Results are uploaded to S3 # This submits an AWS Batch job to run a lot of sims, each within a docker image. Results are uploaded to S3
start-remote-sims: start-remote-sims:
# build the image used for running sims in, and tag it # build the image used for running sims in, and tag it
docker build -f simulations/Dockerfile -t kava/kava-sim:master . docker build -f simulations/Dockerfile -t $(DOCKER_IMAGE_NAME)-sim:master .
# push that image to the hub # push that image to the hub
docker push kava/kava-sim:master docker push $(DOCKER_IMAGE_NAME)-sim:master
# submit an array job on AWS Batch, using 1000 seeds, spot instances # submit an array job on AWS Batch, using 1000 seeds, spot instances
aws batch submit-job \ aws batch submit-job \
-—job-name "master-$(VERSION)" \ -—job-name "master-$(VERSION)" \
-—job-queue “simulation-1-queue-spot" \ -—job-queue “simulation-1-queue-spot" \
-—array-properties size=1000 \ -—array-properties size=1000 \
-—job-definition kava-sim-master \ -—job-definition $(BINARY_NAME)-sim-master \
-—container-override environment=[{SIM_NAME=master-$(VERSION)}] -—container-override environment=[{SIM_NAME=master-$(VERSION)}]
update-kvtool: update-kvtool:

View File

@ -32,15 +32,15 @@ import (
"github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/supply" "github.com/cosmos/cosmos-sdk/x/supply"
"github.com/kava-labs/kava/x/auction" "github.com/0glabs/0g-chain/x/auction"
"github.com/kava-labs/kava/x/bep3" "github.com/0glabs/0g-chain/x/bep3"
"github.com/kava-labs/kava/x/cdp" "github.com/0glabs/0g-chain/x/cdp"
"github.com/kava-labs/kava/x/committee" "github.com/0glabs/0g-chain/x/committee"
"github.com/kava-labs/kava/x/incentive" "github.com/0glabs/0g-chain/x/incentive"
"github.com/kava-labs/kava/x/kavadist" "github.com/0glabs/0g-chain/x/kavadist"
"github.com/kava-labs/kava/x/pricefeed" "github.com/0glabs/0g-chain/x/pricefeed"
"github.com/kava-labs/kava/x/swap" "github.com/0glabs/0g-chain/x/swap"
validatorvesting "github.com/kava-labs/kava/x/validator-vesting" validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting"
) )
type StoreKeysPrefixes struct { type StoreKeysPrefixes struct {

View File

@ -9,7 +9,7 @@ import (
"testing" "testing"
sdkmath "cosmossdk.io/math" sdkmath "cosmossdk.io/math"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
abci "github.com/cometbft/cometbft/abci/types" abci "github.com/cometbft/cometbft/abci/types"
tmbytes "github.com/cometbft/cometbft/libs/bytes" tmbytes "github.com/cometbft/cometbft/libs/bytes"

View File

@ -20,9 +20,9 @@ import (
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
// bep3types "github.com/kava-labs/kava/x/bep3/types" // bep3types "github.com/0glabs/0g-chain/x/bep3/types"
// pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" // pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {

View File

@ -10,8 +10,8 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/ante" "github.com/0glabs/0g-chain/app/ante"
) )
var _ sdk.AnteHandler = (&MockAnteHandler{}).AnteHandle var _ sdk.AnteHandler = (&MockAnteHandler{}).AnteHandle

View File

@ -14,8 +14,8 @@ import (
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/ante" "github.com/0glabs/0g-chain/app/ante"
) )
func newMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a authz.Authorization, expiration time.Time) *authz.MsgGrant { func newMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a authz.Authorization, expiration time.Time) *authz.MsgGrant {

View File

@ -33,13 +33,13 @@ import (
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
// cdptypes "github.com/kava-labs/kava/x/cdp/types" // cdptypes "github.com/0glabs/0g-chain/x/cdp/types"
evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
evmutiltestutil "github.com/kava-labs/kava/x/evmutil/testutil" evmutiltestutil "github.com/0glabs/0g-chain/x/evmutil/testutil"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
// hardtypes "github.com/kava-labs/kava/x/hard/types" // hardtypes "github.com/0glabs/0g-chain/x/hard/types"
// pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" // pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
) )
const ( const (

View File

@ -11,8 +11,8 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/ante" "github.com/0glabs/0g-chain/app/ante"
) )
func mustParseDecCoins(value string) sdk.DecCoins { func mustParseDecCoins(value string) sdk.DecCoins {

View File

@ -12,8 +12,8 @@ import (
vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/ante" "github.com/0glabs/0g-chain/app/ante"
) )
func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing.T) { func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing.T) {

View File

@ -105,16 +105,22 @@ import (
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/kava-labs/kava/app/ante" "github.com/0glabs/0g-chain/app/ante"
kavaparams "github.com/kava-labs/kava/app/params" kavaparams "github.com/0glabs/0g-chain/app/params"
evmutil "github.com/kava-labs/kava/x/evmutil" evmutil "github.com/0glabs/0g-chain/x/evmutil"
evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
validatorvesting "github.com/kava-labs/kava/x/validator-vesting" committee "github.com/0glabs/0g-chain/x/committee/v1"
validatorvestingrest "github.com/kava-labs/kava/x/validator-vesting/client/rest" committeekeeper "github.com/0glabs/0g-chain/x/committee/v1/keeper"
validatorvestingtypes "github.com/kava-labs/kava/x/validator-vesting/types" committeetypes "github.com/0glabs/0g-chain/x/committee/v1/types"
das "github.com/0glabs/0g-chain/x/das/v1"
daskeeper "github.com/0glabs/0g-chain/x/das/v1/keeper"
dastypes "github.com/0glabs/0g-chain/x/das/v1/types"
validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting"
validatorvestingrest "github.com/0glabs/0g-chain/x/validator-vesting/client/rest"
validatorvestingtypes "github.com/0glabs/0g-chain/x/validator-vesting/types"
) )
const ( const (
@ -159,6 +165,8 @@ var (
evmutil.AppModuleBasic{}, evmutil.AppModuleBasic{},
mint.AppModuleBasic{}, mint.AppModuleBasic{},
consensus.AppModuleBasic{}, consensus.AppModuleBasic{},
committee.AppModuleBasic{},
das.AppModuleBasic{},
) )
// module account permissions // module account permissions
@ -235,6 +243,8 @@ type App struct {
transferKeeper ibctransferkeeper.Keeper transferKeeper ibctransferkeeper.Keeper
mintKeeper mintkeeper.Keeper mintKeeper mintkeeper.Keeper
consensusParamsKeeper consensusparamkeeper.Keeper consensusParamsKeeper consensusparamkeeper.Keeper
CommitteeKeeper committeekeeper.Keeper
DasKeeper daskeeper.Keeper
// make scoped keepers public for test purposes // make scoped keepers public for test purposes
ScopedIBCKeeper capabilitykeeper.ScopedKeeper ScopedIBCKeeper capabilitykeeper.ScopedKeeper
@ -299,6 +309,8 @@ func NewApp(
minttypes.StoreKey, minttypes.StoreKey,
consensusparamtypes.StoreKey, consensusparamtypes.StoreKey,
crisistypes.StoreKey, crisistypes.StoreKey,
committeetypes.StoreKey,
dastypes.StoreKey,
) )
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey)
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
@ -540,6 +552,11 @@ func NewApp(
govKeeper.SetLegacyRouter(govRouter) govKeeper.SetLegacyRouter(govRouter)
app.govKeeper = *govKeeper app.govKeeper = *govKeeper
app.CommitteeKeeper = committeekeeper.NewKeeper(
keys[committeetypes.StoreKey], appCodec, app.stakingKeeper,
)
app.DasKeeper = daskeeper.NewKeeper(keys[dastypes.StoreKey], appCodec, app.stakingKeeper)
// create the module manager (Note: Any module instantiated in the module manager that is later modified // create the module manager (Note: Any module instantiated in the module manager that is later modified
// must be passed by reference here.) // must be passed by reference here.)
app.mm = module.NewManager( app.mm = module.NewManager(
@ -599,6 +616,9 @@ func NewApp(
evmutiltypes.ModuleName, evmutiltypes.ModuleName,
consensusparamtypes.ModuleName, consensusparamtypes.ModuleName,
packetforwardtypes.ModuleName, packetforwardtypes.ModuleName,
committeetypes.ModuleName,
dastypes.ModuleName,
) )
// Warning: Some end blockers must run before others. Ensure the dependencies are understood before modifying this list. // Warning: Some end blockers must run before others. Ensure the dependencies are understood before modifying this list.
@ -628,6 +648,8 @@ func NewApp(
minttypes.ModuleName, minttypes.ModuleName,
consensusparamtypes.ModuleName, consensusparamtypes.ModuleName,
packetforwardtypes.ModuleName, packetforwardtypes.ModuleName,
committeetypes.ModuleName,
dastypes.ModuleName,
) )
// Warning: Some init genesis methods must run before others. Ensure the dependencies are understood before modifying this list // Warning: Some init genesis methods must run before others. Ensure the dependencies are understood before modifying this list
@ -656,6 +678,8 @@ func NewApp(
consensusparamtypes.ModuleName, consensusparamtypes.ModuleName,
packetforwardtypes.ModuleName, packetforwardtypes.ModuleName,
crisistypes.ModuleName, // runs the invariants at genesis, should run after other modules crisistypes.ModuleName, // runs the invariants at genesis, should run after other modules
committeetypes.ModuleName,
dastypes.ModuleName,
) )
app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterInvariants(&app.crisisKeeper)

View File

@ -3,7 +3,7 @@ package app
import ( import (
enccodec "github.com/evmos/ethermint/encoding/codec" enccodec "github.com/evmos/ethermint/encoding/codec"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
) )
// MakeEncodingConfig creates an EncodingConfig and registers the app's types on it. // MakeEncodingConfig creates an EncodingConfig and registers the app's types on it.

View File

@ -41,7 +41,7 @@ import (
feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper" feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
) )
var ( var (

22
chaincfg/coin.go Normal file
View File

@ -0,0 +1,22 @@
package chaincfg
import (
sdk "github.com/cosmos/cosmos-sdk/types"
ethaccounts "github.com/ethereum/go-ethereum/accounts"
)
var (
// Bip44CoinType satisfies EIP84. See https://github.com/ethereum/EIPs/issues/84 for more info.
Bip44CoinType uint32 = 60 // TODO: need new coin type for 0g-chain (a0gi)
// BIP44HDPath is the default BIP44 HD path used on Ethereum.
BIP44HDPath = ethaccounts.DefaultBaseDerivationPath.String()
)
// TODO: Implement BIP44CoinType and BIP44HDPath
// SetBip44CoinType sets the global coin type to be used in hierarchical deterministic wallets.
func setBip44CoinType(config *sdk.Config) {
config.SetCoinType(Bip44CoinType)
config.SetPurpose(sdk.Purpose) // Shared
config.SetFullFundraiserPath(BIP44HDPath) //nolint: staticcheck
}

15
chaincfg/config.go Normal file
View File

@ -0,0 +1,15 @@
package chaincfg
import sdk "github.com/cosmos/cosmos-sdk/types"
const (
AppName = "0gchain"
EnvPrefix = "0GCHAIN"
)
func SetSDKConfig() *sdk.Config {
config := sdk.GetConfig()
setBech32Prefixes(config)
// setBip44CoinType(config)
return config
}

28
chaincfg/denoms.go Normal file
View File

@ -0,0 +1,28 @@
package chaincfg
import (
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// DisplayDenom defines the denomination displayed to users in client applications.
DisplayDenom = "a0gi"
// BaseDenom defines to the default denomination used in 0g-chain
BaseDenom = "neuron"
BaseDenomUnit = 18
ConversionMultiplier = 1e18
)
// RegisterDenoms registers the base and display denominations to the SDK.
func RegisterDenoms() {
if err := sdk.RegisterDenom(DisplayDenom, math.LegacyOneDec()); err != nil {
panic(err)
}
if err := sdk.RegisterDenom(BaseDenom, math.LegacyNewDecWithPrec(1, BaseDenomUnit)); err != nil {
panic(err)
}
}

25
chaincfg/homedir.go Normal file
View File

@ -0,0 +1,25 @@
package chaincfg
import (
stdlog "log"
"os"
"path/filepath"
)
const (
HomeDirName = ".0gchain"
)
var (
// DefaultNodeHome default home directories for the application daemon
DefaultNodeHome string
)
func init() {
userHomeDir, err := os.UserHomeDir()
if err != nil {
stdlog.Printf("Failed to get home dir %v", err)
}
DefaultNodeHome = filepath.Join(userHomeDir, HomeDirName)
}

44
chaincfg/prefix.go Normal file
View File

@ -0,0 +1,44 @@
package chaincfg
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// Bech32Prefix defines the Bech32 prefix used for EthAccounts
Bech32Prefix = "0g"
// PrefixAccount is the prefix for account keys
PrefixAccount = "acc"
// PrefixValidator is the prefix for validator keys
PrefixValidator = "val"
// PrefixConsensus is the prefix for consensus keys
PrefixConsensus = "cons"
// PrefixPublic is the prefix for public keys
PrefixPublic = "pub"
// PrefixOperator is the prefix for operator keys
PrefixOperator = "oper"
// PrefixAddress is the prefix for addresses
PrefixAddress = "addr"
// Bech32PrefixAccAddr defines the Bech32 prefix of an account's address
Bech32PrefixAccAddr = Bech32Prefix
// Bech32PrefixAccPub defines the Bech32 prefix of an account's public key
Bech32PrefixAccPub = Bech32Prefix + PrefixPublic
// Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address
Bech32PrefixValAddr = Bech32Prefix + PrefixValidator + PrefixOperator
// Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key
Bech32PrefixValPub = Bech32Prefix + PrefixValidator + PrefixOperator + PrefixPublic
// Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address
Bech32PrefixConsAddr = Bech32Prefix + PrefixValidator + PrefixConsensus
// Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key
Bech32PrefixConsPub = Bech32Prefix + PrefixValidator + PrefixConsensus + PrefixPublic
)
// setBech32Prefixes sets the global prefixes to be used when serializing addresses and public keys to Bech32 strings.
func setBech32Prefixes(config *sdk.Config) {
config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub)
config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub)
config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub)
}

View File

@ -28,7 +28,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/slashing"
"github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
) )
const ( const (

View File

@ -16,7 +16,7 @@ The Kava gRPC client is a tool for making gRPC queries on a Kava chain.
package main package main
import ( import (
kavaGrpc "github.com/kava-labs/kava/client/grpc" kavaGrpc "github.com/0glabs/0g-chain/client/grpc"
) )
grpcUrl := "https://grpc.kava.io:443" grpcUrl := "https://grpc.kava.io:443"
client, err := kavaGrpc.NewClient(grpcUrl) client, err := kavaGrpc.NewClient(grpcUrl)
@ -46,7 +46,7 @@ Example: Query Kava module `x/evmutil` for params
```go ```go
import ( import (
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
) )
rsp, err := client.Query.Evmutil.Params( rsp, err := client.Query.Evmutil.Params(

View File

@ -3,8 +3,8 @@ package grpc
import ( import (
"errors" "errors"
"github.com/kava-labs/kava/client/grpc/query" "github.com/0glabs/0g-chain/client/grpc/query"
"github.com/kava-labs/kava/client/grpc/util" "github.com/0glabs/0g-chain/client/grpc/util"
) )
// KavaGrpcClient enables the usage of kava grpc query clients and query utils // KavaGrpcClient enables the usage of kava grpc query clients and query utils

View File

@ -3,7 +3,7 @@ package grpc_test
import ( import (
"testing" "testing"
"github.com/kava-labs/kava/client/grpc" "github.com/0glabs/0g-chain/client/grpc"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )

View File

@ -24,21 +24,21 @@ import (
evmtypes "github.com/evmos/ethermint/x/evm/types" evmtypes "github.com/evmos/ethermint/x/evm/types"
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
// auctiontypes "github.com/kava-labs/kava/x/auction/types" // auctiontypes "github.com/0glabs/0g-chain/x/auction/types"
// bep3types "github.com/kava-labs/kava/x/bep3/types" // bep3types "github.com/0glabs/0g-chain/x/bep3/types"
// cdptypes "github.com/kava-labs/kava/x/cdp/types" // cdptypes "github.com/0glabs/0g-chain/x/cdp/types"
// committeetypes "github.com/kava-labs/kava/x/committee/types" // committeetypes "github.com/0glabs/0g-chain/x/committee/types"
// communitytypes "github.com/kava-labs/kava/x/community/types" // communitytypes "github.com/0glabs/0g-chain/x/community/types"
// earntypes "github.com/kava-labs/kava/x/earn/types" // earntypes "github.com/0glabs/0g-chain/x/earn/types"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
// hardtypes "github.com/kava-labs/kava/x/hard/types" // hardtypes "github.com/0glabs/0g-chain/x/hard/types"
// incentivetypes "github.com/kava-labs/kava/x/incentive/types" // incentivetypes "github.com/0glabs/0g-chain/x/incentive/types"
// issuancetypes "github.com/kava-labs/kava/x/issuance/types" // issuancetypes "github.com/0glabs/0g-chain/x/issuance/types"
// kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" // kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types"
// liquidtypes "github.com/kava-labs/kava/x/liquid/types" // liquidtypes "github.com/0glabs/0g-chain/x/liquid/types"
// pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" // pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types"
// savingstypes "github.com/kava-labs/kava/x/savings/types" // savingstypes "github.com/0glabs/0g-chain/x/savings/types"
// swaptypes "github.com/kava-labs/kava/x/swap/types" // swaptypes "github.com/0glabs/0g-chain/x/swap/types"
) )
// QueryClient is a wrapper with all Cosmos and Kava grpc query clients // QueryClient is a wrapper with all Cosmos and Kava grpc query clients

View File

@ -3,7 +3,7 @@ package query_test
import ( import (
"testing" "testing"
"github.com/kava-labs/kava/client/grpc/query" "github.com/0glabs/0g-chain/client/grpc/query"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )

View File

@ -7,9 +7,9 @@ import (
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
query "github.com/kava-labs/kava/client/grpc/query" query "github.com/0glabs/0g-chain/client/grpc/query"
) )
// Util contains utility functions for the Kava gRPC client // Util contains utility functions for the Kava gRPC client

View File

@ -13,6 +13,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
simappparams "cosmossdk.io/simapp/params" simappparams "cosmossdk.io/simapp/params"
"github.com/0glabs/0g-chain/client/rest"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
@ -20,7 +21,6 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/client/rest"
) )
func TestBaseReq_Sanitize(t *testing.T) { func TestBaseReq_Sanitize(t *testing.T) {

View File

@ -1,4 +1,4 @@
package cmd package zgchaind
import ( import (
"errors" "errors"
@ -23,8 +23,8 @@ import (
"github.com/spf13/cast" "github.com/spf13/cast"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
) )
const ( const (

View File

@ -1,4 +1,4 @@
package cmd package zgchaind
import ( import (
"encoding/json" "encoding/json"
@ -9,8 +9,8 @@ import (
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
) )
func AssertInvariantsCmd(config params.EncodingConfig) *cobra.Command { func AssertInvariantsCmd(config params.EncodingConfig) *cobra.Command {

View File

@ -1,5 +1,5 @@
// Sourced from https://github.com/evmos/ethermint/blob/main/cmd/ethermintd/genaccounts.go // Sourced from https://github.com/evmos/ethermint/blob/main/cmd/ethermintd/genaccounts.go
package cmd package zgchaind
import ( import (
"bufio" "bufio"

View File

@ -1,4 +1,4 @@
package cmd package zgchaind
import ( import (
"bufio" "bufio"

View File

@ -1,4 +1,4 @@
package cmd package zgchaind
import ( import (
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
@ -7,7 +7,7 @@ import (
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
) )
// newQueryCmd creates all the commands for querying blockchain state. // newQueryCmd creates all the commands for querying blockchain state.

View File

@ -1,4 +1,4 @@
package cmd package zgchaind
import ( import (
"fmt" "fmt"
@ -23,21 +23,16 @@ import (
servercfg "github.com/evmos/ethermint/server/config" servercfg "github.com/evmos/ethermint/server/config"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
"github.com/kava-labs/kava/cmd/kava/cmd/rocksdb" "github.com/0glabs/0g-chain/chaincfg"
"github.com/kava-labs/kava/cmd/kava/opendb" "github.com/0glabs/0g-chain/cmd/opendb"
"github.com/0glabs/0g-chain/cmd/rocksdb"
) )
// EnvPrefix is the prefix environment variables must have to configure the app. // NewRootCmd creates a new root command for the 0g-chain blockchain.
const EnvPrefix = "KAVA"
// NewRootCmd creates a new root command for the kava blockchain.
func NewRootCmd() *cobra.Command { func NewRootCmd() *cobra.Command {
app.SetSDKConfig().Seal()
encodingConfig := app.MakeEncodingConfig() encodingConfig := app.MakeEncodingConfig()
initClientCtx := client.Context{}. initClientCtx := client.Context{}.
WithCodec(encodingConfig.Marshaler). WithCodec(encodingConfig.Marshaler).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry). WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
@ -46,13 +41,12 @@ func NewRootCmd() *cobra.Command {
WithInput(os.Stdin). WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}). WithAccountRetriever(types.AccountRetriever{}).
WithBroadcastMode(flags.FlagBroadcastMode). WithBroadcastMode(flags.FlagBroadcastMode).
WithHomeDir(app.DefaultNodeHome). WithHomeDir(chaincfg.DefaultNodeHome).
WithKeyringOptions(hd.EthSecp256k1Option()). WithKeyringOptions(hd.EthSecp256k1Option()).
WithViper(EnvPrefix) WithViper(chaincfg.EnvPrefix)
rootCmd := &cobra.Command{ rootCmd := &cobra.Command{
Use: "kava", Use: chaincfg.AppName,
Short: "Daemon and CLI for the Kava blockchain.", Short: "Daemon and CLI for the 0g-chain blockchain.",
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
cmd.SetOut(cmd.OutOrStdout()) cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr()) cmd.SetErr(cmd.ErrOrStderr())
@ -71,7 +65,7 @@ func NewRootCmd() *cobra.Command {
return err return err
} }
customAppTemplate, customAppConfig := servercfg.AppConfig("ukava") customAppTemplate, customAppConfig := servercfg.AppConfig(chaincfg.BaseDenom)
return server.InterceptConfigsPreRunHandler( return server.InterceptConfigsPreRunHandler(
cmd, cmd,
@ -82,12 +76,12 @@ func NewRootCmd() *cobra.Command {
}, },
} }
addSubCmds(rootCmd, encodingConfig, app.DefaultNodeHome) addSubCmds(rootCmd, encodingConfig, chaincfg.DefaultNodeHome)
return rootCmd return rootCmd
} }
// addSubCmds registers all the sub commands used by kava. // addSubCmds registers all the sub commands used by 0g-chain.
func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, defaultNodeHome string) { func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, defaultNodeHome string) {
gentxModule, ok := app.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic) gentxModule, ok := app.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic)
if !ok { if !ok {
@ -116,7 +110,7 @@ func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, de
opts := ethermintserver.StartOptions{ opts := ethermintserver.StartOptions{
AppCreator: ac.newApp, AppCreator: ac.newApp,
DefaultNodeHome: app.DefaultNodeHome, DefaultNodeHome: chaincfg.DefaultNodeHome,
DBOpener: opendb.OpenDB, DBOpener: opendb.OpenDB,
} }
// ethermintserver adds additional flags to start the JSON-RPC server for evm support // ethermintserver adds additional flags to start the JSON-RPC server for evm support
@ -131,7 +125,7 @@ func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, de
rootCmd.AddCommand( rootCmd.AddCommand(
newQueryCmd(), newQueryCmd(),
newTxCmd(), newTxCmd(),
keyCommands(app.DefaultNodeHome), keyCommands(chaincfg.DefaultNodeHome),
rocksdb.RocksDBCmd, rocksdb.RocksDBCmd,
newShardCmd(opts), newShardCmd(opts),
) )

View File

@ -1,10 +1,10 @@
package cmd package zgchaind
import ( import (
"fmt" "fmt"
"strings" "strings"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/spf13/cobra" "github.com/spf13/cobra"
dbm "github.com/cometbft/cometbft-db" dbm "github.com/cometbft/cometbft-db"

View File

@ -1,4 +1,4 @@
package cmd package zgchaind
import ( import (
"context" "context"

View File

@ -1,4 +1,4 @@
package cmd package zgchaind
import ( import (
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
@ -6,7 +6,7 @@ import (
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
) )
// newTxCmd creates all commands for submitting blockchain transactions. // newTxCmd creates all commands for submitting blockchain transactions.

View File

@ -1,25 +0,0 @@
package main
import (
"os"
"github.com/cosmos/cosmos-sdk/server"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/cmd/kava/cmd"
)
func main() {
rootCmd := cmd.NewRootCmd()
if err := svrcmd.Execute(rootCmd, cmd.EnvPrefix, app.DefaultNodeHome); err != nil {
switch e := err.(type) {
case server.ErrorCode:
os.Exit(e.Code)
default:
os.Exit(1)
}
}
}

28
cmd/main.go Normal file
View File

@ -0,0 +1,28 @@
package main
import (
"os"
"github.com/cosmos/cosmos-sdk/server"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
"github.com/0glabs/0g-chain/chaincfg"
chain "github.com/0glabs/0g-chain/cmd/0gchaind"
)
func main() {
chaincfg.SetSDKConfig().Seal()
chaincfg.RegisterDenoms()
rootCmd := chain.NewRootCmd()
if err := svrcmd.Execute(rootCmd, chaincfg.EnvPrefix, chaincfg.DefaultNodeHome); err != nil {
switch e := err.(type) {
case server.ErrorCode:
os.Exit(e.Code)
default:
os.Exit(1)
}
}
}

View File

@ -14,9 +14,9 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/0glabs/0g-chain/cmd/opendb"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server"
"github.com/kava-labs/kava/cmd/kava/opendb"
"github.com/linxGnu/grocksdb" "github.com/linxGnu/grocksdb"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"

58
crypto/vrf/algorithm.go Normal file
View File

@ -0,0 +1,58 @@
package vrf
import (
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
)
var (
// SupportedAlgorithms defines the list of signing algorithms used on Evmos:
// - eth_secp256k1 (Ethereum)
// - secp256k1 (Tendermint)
SupportedAlgorithms = keyring.SigningAlgoList{VrfAlgo}
// SupportedAlgorithmsLedger defines the list of signing algorithms used on Evmos for the Ledger device:
// - eth_secp256k1 (Ethereum)
// - secp256k1 (Tendermint)
SupportedAlgorithmsLedger = keyring.SigningAlgoList{VrfAlgo}
)
func VrfOption() keyring.Option {
return func(options *keyring.Options) {
options.SupportedAlgos = SupportedAlgorithms
options.SupportedAlgosLedger = SupportedAlgorithmsLedger
}
}
const (
VrfType = hd.PubKeyType(KeyType)
)
var (
_ keyring.SignatureAlgo = VrfAlgo
VrfAlgo = vrfAlgo{}
)
type vrfAlgo struct{}
func (s vrfAlgo) Name() hd.PubKeyType {
return VrfType
}
func (s vrfAlgo) Derive() hd.DeriveFn {
return func(mnemonic, bip39Passphrase, path string) ([]byte, error) {
key, err := GenerateKey()
if err != nil {
return nil, err
}
return key.Bytes(), nil
}
}
func (s vrfAlgo) Generate() hd.GenerateFn {
return func(bz []byte) cryptotypes.PrivKey {
key, _ := GenerateKey()
return key
}
}

496
crypto/vrf/keys.pb.go Normal file
View File

@ -0,0 +1,496 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: crypto/vrf/keys.proto
package vrf
import (
fmt "fmt"
_ "github.com/cosmos/gogoproto/gogoproto"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// PubKey defines a type alias for an vrf.PublicKey that implements
// Vrf's PubKey interface. It represents the 32-byte compressed public
// key format.
type PubKey struct {
// key is the public key in byte form
Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
}
func (m *PubKey) Reset() { *m = PubKey{} }
func (*PubKey) ProtoMessage() {}
func (*PubKey) Descriptor() ([]byte, []int) {
return fileDescriptor_eae59d1af27f5957, []int{0}
}
func (m *PubKey) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PubKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PubKey.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PubKey) XXX_Merge(src proto.Message) {
xxx_messageInfo_PubKey.Merge(m, src)
}
func (m *PubKey) XXX_Size() int {
return m.Size()
}
func (m *PubKey) XXX_DiscardUnknown() {
xxx_messageInfo_PubKey.DiscardUnknown(m)
}
var xxx_messageInfo_PubKey proto.InternalMessageInfo
func (m *PubKey) GetKey() []byte {
if m != nil {
return m.Key
}
return nil
}
// PrivKey defines a type alias for an vrf.PrivateKey that implements
// Vrf's PrivateKey interface.
type PrivKey struct {
// key is the private key in byte form
Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
}
func (m *PrivKey) Reset() { *m = PrivKey{} }
func (m *PrivKey) String() string { return proto.CompactTextString(m) }
func (*PrivKey) ProtoMessage() {}
func (*PrivKey) Descriptor() ([]byte, []int) {
return fileDescriptor_eae59d1af27f5957, []int{1}
}
func (m *PrivKey) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PrivKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PrivKey.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PrivKey) XXX_Merge(src proto.Message) {
xxx_messageInfo_PrivKey.Merge(m, src)
}
func (m *PrivKey) XXX_Size() int {
return m.Size()
}
func (m *PrivKey) XXX_DiscardUnknown() {
xxx_messageInfo_PrivKey.DiscardUnknown(m)
}
var xxx_messageInfo_PrivKey proto.InternalMessageInfo
func (m *PrivKey) GetKey() []byte {
if m != nil {
return m.Key
}
return nil
}
func init() {
proto.RegisterType((*PubKey)(nil), "crypto.vrf.PubKey")
proto.RegisterType((*PrivKey)(nil), "crypto.vrf.PrivKey")
}
func init() { proto.RegisterFile("crypto/vrf/keys.proto", fileDescriptor_eae59d1af27f5957) }
var fileDescriptor_eae59d1af27f5957 = []byte{
// 174 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0x2e, 0xaa, 0x2c,
0x28, 0xc9, 0xd7, 0x2f, 0x2b, 0x4a, 0xd3, 0xcf, 0x4e, 0xad, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f,
0xc9, 0x17, 0xe2, 0x82, 0x08, 0xeb, 0x95, 0x15, 0xa5, 0x49, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83,
0x85, 0xf5, 0x41, 0x2c, 0x88, 0x0a, 0x25, 0x05, 0x2e, 0xb6, 0x80, 0xd2, 0x24, 0xef, 0xd4, 0x4a,
0x21, 0x01, 0x2e, 0xe6, 0xec, 0xd4, 0x4a, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x9e, 0x20, 0x10, 0xd3,
0x8a, 0x65, 0xc6, 0x02, 0x79, 0x06, 0x25, 0x69, 0x2e, 0xf6, 0x80, 0xa2, 0xcc, 0x32, 0xac, 0x4a,
0x9c, 0xec, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09,
0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x35, 0x3d, 0xb3,
0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0x20, 0x3d, 0x27, 0x31, 0xa9, 0x58, 0xdf,
0x20, 0x5d, 0x37, 0x39, 0x23, 0x31, 0x33, 0x4f, 0x1f, 0xe1, 0xd8, 0x24, 0x36, 0xb0, 0x33, 0x8c,
0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xdb, 0xb8, 0x32, 0x07, 0xc1, 0x00, 0x00, 0x00,
}
func (m *PubKey) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PubKey) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PubKey) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintKeys(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *PrivKey) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PrivKey) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PrivKey) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintKeys(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintKeys(dAtA []byte, offset int, v uint64) int {
offset -= sovKeys(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *PubKey) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Key)
if l > 0 {
n += 1 + l + sovKeys(uint64(l))
}
return n
}
func (m *PrivKey) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Key)
if l > 0 {
n += 1 + l + sovKeys(uint64(l))
}
return n
}
func sovKeys(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozKeys(x uint64) (n int) {
return sovKeys(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *PubKey) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowKeys
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PubKey: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PubKey: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowKeys
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthKeys
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthKeys
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...)
if m.Key == nil {
m.Key = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipKeys(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthKeys
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *PrivKey) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowKeys
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PrivKey: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PrivKey: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowKeys
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthKeys
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthKeys
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...)
if m.Key == nil {
m.Key = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipKeys(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthKeys
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipKeys(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowKeys
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowKeys
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowKeys
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthKeys
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupKeys
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthKeys
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthKeys = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowKeys = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupKeys = fmt.Errorf("proto: unexpected end of group")
)

194
crypto/vrf/vrf.go Normal file
View File

@ -0,0 +1,194 @@
package vrf
import (
"bytes"
"crypto/subtle"
"fmt"
errorsmod "cosmossdk.io/errors"
tmcrypto "github.com/cometbft/cometbft/crypto"
vrfalgo "github.com/coniks-sys/coniks-go/crypto/vrf"
"github.com/cosmos/cosmos-sdk/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
errortypes "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/ethereum/go-ethereum/common"
)
const (
// PrivKeySize defines the size of the PrivKey bytes
PrivKeySize = 64
// PubKeySize defines the size of the PubKey bytes
PubKeySize = 32
// KeyType is the string constant for the vrf algorithm
KeyType = "vrf"
)
// Amino encoding names
const (
// PrivKeyName defines the amino encoding name for the vrf private key
PrivKeyName = "vrf/PrivKey"
// PubKeyName defines the amino encoding name for the vrf public key
PubKeyName = "vrf/PubKey"
)
// ----------------------------------------------------------------------------
// vrf Private Key
var (
_ cryptotypes.PrivKey = &PrivKey{}
_ codec.AminoMarshaler = &PrivKey{}
)
// GenerateKey generates a new random private key. It returns an error upon
// failure.
func GenerateKey() (*PrivKey, error) {
priv, err := vrfalgo.GenerateKey(nil)
if err != nil {
return nil, err
}
return &PrivKey{
Key: priv,
}, nil
}
func (privKey PrivKey) getVrfPrivateKey() vrfalgo.PrivateKey {
return vrfalgo.PrivateKey(privKey.Key)
}
// Bytes returns the byte representation of the Private Key.
func (privKey PrivKey) Bytes() []byte {
bz := make([]byte, len(privKey.Key))
copy(bz, privKey.Key)
return bz
}
// PubKey returns the private key's public key. If the privkey is not valid
// it returns a nil value.
func (privKey PrivKey) PubKey() cryptotypes.PubKey {
pk, _ := vrfalgo.PrivateKey(privKey.Key).Public()
return &PubKey{
Key: pk,
}
}
// Equals returns true if two private keys are equal and false otherwise.
func (privKey PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool {
return privKey.Type() == other.Type() && subtle.ConstantTimeCompare(privKey.Bytes(), other.Bytes()) == 1
}
// Type returns vrf
func (privKey PrivKey) Type() string {
return KeyType
}
// Compute generates the vrf value for the byte slice m using the
// underlying private key sk.
func (privKey PrivKey) Sign(digestBz []byte) ([]byte, error) {
sk := privKey.getVrfPrivateKey()
return sk.Compute(digestBz), nil
}
// MarshalAmino overrides Amino binary marshaling.
func (privKey PrivKey) MarshalAmino() ([]byte, error) {
return privKey.Key, nil
}
// UnmarshalAmino overrides Amino binary marshaling.
func (privKey *PrivKey) UnmarshalAmino(bz []byte) error {
if len(bz) != PrivKeySize {
return fmt.Errorf("invalid privkey size, expected %d got %d", PrivKeySize, len(bz))
}
privKey.Key = bz
return nil
}
// MarshalAminoJSON overrides Amino JSON marshaling.
func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) {
// When we marshal to Amino JSON, we don't marshal the "key" field itself,
// just its contents (i.e. the key bytes).
return privKey.MarshalAmino()
}
// UnmarshalAminoJSON overrides Amino JSON marshaling.
func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error {
return privKey.UnmarshalAmino(bz)
}
// ----------------------------------------------------------------------------
// vrf Public Key
var (
_ cryptotypes.PubKey = &PubKey{}
_ codec.AminoMarshaler = &PubKey{}
)
// func (pubKey PubKey) getVrfPublicKey() vrfalgo.PublicKey {
// return vrfalgo.PublicKey(pubKey.Key)
// }
// Address returns the address of the ECDSA public key.
// The function will return an empty address if the public key is invalid.
func (pubKey PubKey) Address() tmcrypto.Address {
return tmcrypto.Address(common.BytesToAddress(pubKey.Key).Bytes())
}
// Bytes returns the raw bytes of the ECDSA public key.
func (pubKey PubKey) Bytes() []byte {
bz := make([]byte, len(pubKey.Key))
copy(bz, pubKey.Key)
return bz
}
// String implements the fmt.Stringer interface.
func (pubKey PubKey) String() string {
return fmt.Sprintf("vrf{%X}", pubKey.Key)
}
// Type returns vrf
func (pubKey PubKey) Type() string {
return KeyType
}
// Equals returns true if the pubkey type is the same and their bytes are deeply equal.
func (pubKey PubKey) Equals(other cryptotypes.PubKey) bool {
return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes())
}
// Verify returns true iff vrf=Compute(m) for the sk that
// corresponds to pk.
func (pubKey PubKey) VerifySignature(msg, sig []byte) bool {
panic("not implement")
}
// MarshalAmino overrides Amino binary marshaling.
func (pubKey PubKey) MarshalAmino() ([]byte, error) {
return pubKey.Key, nil
}
// UnmarshalAmino overrides Amino binary marshaling.
func (pubKey *PubKey) UnmarshalAmino(bz []byte) error {
if len(bz) != PubKeySize {
return errorsmod.Wrapf(errortypes.ErrInvalidPubKey, "invalid pubkey size, expected %d, got %d", PubKeySize, len(bz))
}
pubKey.Key = bz
return nil
}
// MarshalAminoJSON overrides Amino JSON marshaling.
func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) {
// When we marshal to Amino JSON, we don't marshal the "key" field itself,
// just its contents (i.e. the key bytes).
return pubKey.MarshalAmino()
}
// UnmarshalAminoJSON overrides Amino JSON marshaling.
func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error {
return pubKey.UnmarshalAmino(bz)
}

96
crypto/vrf/vrf_test.go Normal file
View File

@ -0,0 +1,96 @@
package vrf
import (
"testing"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"encoding/base64"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/codec"
)
func TestPrivKey(t *testing.T) {
// validate type and equality
privKey, err := GenerateKey()
require.NoError(t, err)
require.Implements(t, (*cryptotypes.PrivKey)(nil), privKey)
// validate inequality
privKey2, err := GenerateKey()
require.NoError(t, err)
require.False(t, privKey.Equals(privKey2))
}
func TestPrivKey_PubKey(t *testing.T) {
privKey, err := GenerateKey()
require.NoError(t, err)
// validate type and equality
pubKey := &PubKey{
Key: privKey.PubKey().Bytes(),
}
require.Implements(t, (*cryptotypes.PubKey)(nil), pubKey)
// validate inequality
privKey2, err := GenerateKey()
require.NoError(t, err)
require.False(t, pubKey.Equals(privKey2.PubKey()))
}
func TestMarshalAmino(t *testing.T) {
aminoCdc := codec.NewLegacyAmino()
privKey, err := GenerateKey()
require.NoError(t, err)
pubKey := privKey.PubKey().(*PubKey)
testCases := []struct {
desc string
msg codec.AminoMarshaler
typ interface{}
expBinary []byte
expJSON string
}{
{
"vrf private key",
privKey,
&PrivKey{},
append([]byte{64}, privKey.Bytes()...), // Length-prefixed.
"\"" + base64.StdEncoding.EncodeToString(privKey.Bytes()) + "\"",
},
{
"vrf public key",
pubKey,
&PubKey{},
append([]byte{32}, pubKey.Bytes()...), // Length-prefixed.
"\"" + base64.StdEncoding.EncodeToString(pubKey.Bytes()) + "\"",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Do a round trip of encoding/decoding binary.
bz, err := aminoCdc.Marshal(tc.msg)
require.NoError(t, err)
require.Equal(t, tc.expBinary, bz)
err = aminoCdc.Unmarshal(bz, tc.typ)
require.NoError(t, err)
require.Equal(t, tc.msg, tc.typ)
// Do a round trip of encoding/decoding JSON.
bz, err = aminoCdc.MarshalJSON(tc.msg)
require.NoError(t, err)
require.Equal(t, tc.expJSON, string(bz))
err = aminoCdc.UnmarshalJSON(bz, tc.typ)
require.NoError(t, err)
require.Equal(t, tc.msg, tc.typ)
})
}
}

6
go.mod
View File

@ -1,4 +1,4 @@
module github.com/kava-labs/kava module github.com/0glabs/0g-chain
go 1.21 go 1.21
@ -9,6 +9,7 @@ require (
github.com/cenkalti/backoff/v4 v4.1.3 github.com/cenkalti/backoff/v4 v4.1.3
github.com/cometbft/cometbft v0.37.4 github.com/cometbft/cometbft v0.37.4
github.com/cometbft/cometbft-db v0.9.1 github.com/cometbft/cometbft-db v0.9.1
github.com/coniks-sys/coniks-go v0.0.0-20180722014011-11acf4819b71
github.com/cosmos/cosmos-proto v1.0.0-beta.4 github.com/cosmos/cosmos-proto v1.0.0-beta.4
github.com/cosmos/cosmos-sdk v0.47.10 github.com/cosmos/cosmos-sdk v0.47.10
github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/go-bip39 v1.0.0
@ -18,7 +19,6 @@ require (
github.com/ethereum/go-ethereum v1.10.26 github.com/ethereum/go-ethereum v1.10.26
github.com/evmos/ethermint v0.21.0 github.com/evmos/ethermint v0.21.0
github.com/go-kit/kit v0.12.0 github.com/go-kit/kit v0.12.0
github.com/gogo/protobuf v1.3.2
github.com/golang/protobuf v1.5.3 github.com/golang/protobuf v1.5.3
github.com/gorilla/mux v1.8.0 github.com/gorilla/mux v1.8.0
github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0
@ -111,6 +111,7 @@ require (
github.com/go-stack/stack v1.8.1 // indirect github.com/go-stack/stack v1.8.1 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gogo/googleapis v1.4.1 // indirect github.com/gogo/googleapis v1.4.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/glog v1.1.2 // indirect github.com/golang/glog v1.1.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/mock v1.6.0 // indirect github.com/golang/mock v1.6.0 // indirect
@ -183,7 +184,6 @@ require (
github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect
github.com/status-im/keycard-go v0.2.0 // indirect github.com/status-im/keycard-go v0.2.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect
github.com/tendermint/go-amino v0.16.0 // indirect github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tidwall/btree v1.6.0 // indirect github.com/tidwall/btree v1.6.0 // indirect

2
go.sum
View File

@ -396,6 +396,8 @@ github.com/coinbase/rosetta-sdk-go v0.7.9 h1:lqllBjMnazTjIqYrOGv8h8jxjg9+hJazIGZ
github.com/coinbase/rosetta-sdk-go v0.7.9/go.mod h1:0/knutI7XGVqXmmH4OQD8OckFrbQ8yMsUZTG7FXCR2M= github.com/coinbase/rosetta-sdk-go v0.7.9/go.mod h1:0/knutI7XGVqXmmH4OQD8OckFrbQ8yMsUZTG7FXCR2M=
github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4=
github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak=
github.com/coniks-sys/coniks-go v0.0.0-20180722014011-11acf4819b71 h1:MFLTqgfJclmtaQ1SRUrWwmDX/1UBok3XWUethkJ2swQ=
github.com/coniks-sys/coniks-go v0.0.0-20180722014011-11acf4819b71/go.mod h1:TrHYHH4Wze7v7Hkwu1MH1W+mCPQKM+gs+PicdEV14o8=
github.com/consensys/bavard v0.1.8-0.20210406032232-f3452dc9b572/go.mod h1:Bpd0/3mZuaj6Sj+PqrmIquiOKy397AKGThQPaGzNXAQ= github.com/consensys/bavard v0.1.8-0.20210406032232-f3452dc9b572/go.mod h1:Bpd0/3mZuaj6Sj+PqrmIquiOKy397AKGThQPaGzNXAQ=
github.com/consensys/bavard v0.1.8-0.20210915155054-088da2f7f54a/go.mod h1:9ItSMtA/dXMAiL7BG6bqW2m3NdSEObYWoH223nGHukI= github.com/consensys/bavard v0.1.8-0.20210915155054-088da2f7f54a/go.mod h1:9ItSMtA/dXMAiL7BG6bqW2m3NdSEObYWoH223nGHukI=
github.com/consensys/gnark-crypto v0.4.1-0.20210426202927-39ac3d4b3f1f/go.mod h1:815PAHg3wvysy0SyIqanF8gZ0Y1wjk/hrDHD/iT88+Q= github.com/consensys/gnark-crypto v0.4.1-0.20210426202927-39ac3d4b3f1f/go.mod h1:815PAHg3wvysy0SyIqanF8gZ0Y1wjk/hrDHD/iT88+Q=

View File

@ -0,0 +1,61 @@
package client
import (
"context"
"time"
"github.com/0glabs/0g-evmos/helper/da/light"
"github.com/pkg/errors"
)
type DaLightRpcClient interface {
Sample(ctx context.Context, streamId, headerHash []byte, blobIdx, times uint32) (bool, error)
Destroy()
GetInstanceCount() int
}
type daLightClient struct {
maxInstance int
pool ConnectionPool
}
func NewDaLightClient(address string, instanceLimit int) DaLightRpcClient {
return &daLightClient{
maxInstance: instanceLimit,
pool: NewConnectionPool(address, instanceLimit, 10*time.Minute),
}
}
func (c *daLightClient) Sample(ctx context.Context, streamId, headerHash []byte, blobIdx, times uint32) (bool, error) {
connection, err := c.pool.GetConnection()
if err != nil {
return false, errors.Wrap(err, "failed to connect to da light server")
}
defer c.pool.ReleaseConnection(connection)
req := &light.SampleRequest{
StreamId: streamId,
BatchHeaderHash: headerHash,
BlobIndex: blobIdx,
Times: times,
}
client := light.NewLightClient(connection)
reply, err := client.Sample(ctx, req)
if err != nil {
return false, errors.Wrap(err, "failed to sample from da light server")
}
return reply.Success, nil
}
func (c *daLightClient) Destroy() {
if c.pool != nil {
c.pool.Close()
c.pool = nil
}
}
func (c *daLightClient) GetInstanceCount() int {
return c.maxInstance
}

101
helper/da/client/pool.go Normal file
View File

@ -0,0 +1,101 @@
package client
import (
"errors"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials/insecure"
)
type ConnectionPool interface {
GetConnection() (*grpc.ClientConn, error)
ReleaseConnection(*grpc.ClientConn)
Close()
}
type connectionPoolImpl struct {
address string
maxSize int
timeout time.Duration
param grpc.ConnectParams
mu sync.Mutex
pool []*grpc.ClientConn
}
func NewConnectionPool(address string, maxSize int, timeout time.Duration) ConnectionPool {
return &connectionPoolImpl{
address: address,
maxSize: maxSize,
timeout: timeout,
param: grpc.ConnectParams{
Backoff: backoff.Config{
BaseDelay: 1.0 * time.Second,
Multiplier: 1.5,
Jitter: 0.2,
MaxDelay: 30 * time.Second,
},
MinConnectTimeout: 30 * time.Second,
},
pool: make([]*grpc.ClientConn, 0, maxSize),
}
}
func (p *connectionPoolImpl) GetConnection() (*grpc.ClientConn, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool == nil {
return nil, errors.New("connection pool is closed")
}
// Check if there's any available connection in the pool
if len(p.pool) > 0 {
conn := p.pool[0]
p.pool = p.pool[1:]
return conn, nil
}
// If the pool is empty, create a new connection
conn, err := grpc.Dial(p.address, grpc.WithBlock(),
grpc.WithConnectParams(p.param),
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, err
}
return conn, nil
}
func (p *connectionPoolImpl) ReleaseConnection(conn *grpc.ClientConn) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool != nil {
// If the pool is full, close the connection
if len(p.pool) >= p.maxSize {
conn.Close()
return
}
// Add the connection back to the pool
p.pool = append(p.pool, conn)
} else {
conn.Close()
}
}
func (p *connectionPoolImpl) Close() {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool != nil {
for _, conn := range p.pool {
conn.Close()
}
p.pool = nil
}
}

26
helper/da/go.mod Normal file
View File

@ -0,0 +1,26 @@
module github.com/0glabs/0g-evmos/helper/da
go 1.20
require (
github.com/json-iterator/go v1.1.12
github.com/lesismal/nbio v1.5.4
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.32.0
google.golang.org/grpc v1.63.2
google.golang.org/protobuf v1.33.0
)
require (
github.com/lesismal/llib v1.1.13 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/stretchr/testify v1.8.4 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect
)

60
helper/da/go.sum Normal file
View File

@ -0,0 +1,60 @@
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
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/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/lesismal/llib v1.1.13 h1:+w1+t0PykXpj2dXQck0+p6vdC9/mnbEXHgUy/HXDGfE=
github.com/lesismal/llib v1.1.13/go.mod h1:70tFXXe7P1FZ02AU9l8LgSOK7d7sRrpnkUr3rd3gKSg=
github.com/lesismal/nbio v1.5.4 h1:fZ6FOVZOBm7nFuudYsq+WyHJuM2UNuPdlvF/1LVa6lo=
github.com/lesismal/nbio v1.5.4/go.mod h1:mvfYBAA1jmrafXf2XvkM28jWkMTfA5jGks+HKDBMmOc=
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=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.0.0-20210513122933-cd7d49e622d5/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de h1:cZGRis4/ot9uVm639a+rHCUaG0JJHEsdyzSQTMX+suY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY=
google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM=
google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

397
helper/da/light/light.pb.go Normal file
View File

@ -0,0 +1,397 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v4.25.3
// source: light/light.proto
package light
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// SampleRequest contains the blob to sample (by batch and blob index) and required sample times
type SampleRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
StreamId []byte `protobuf:"bytes,1,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
BatchHeaderHash []byte `protobuf:"bytes,2,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"`
BlobIndex uint32 `protobuf:"varint,3,opt,name=blob_index,json=blobIndex,proto3" json:"blob_index,omitempty"`
Times uint32 `protobuf:"varint,4,opt,name=times,proto3" json:"times,omitempty"`
}
func (x *SampleRequest) Reset() {
*x = SampleRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SampleRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SampleRequest) ProtoMessage() {}
func (x *SampleRequest) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SampleRequest.ProtoReflect.Descriptor instead.
func (*SampleRequest) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{0}
}
func (x *SampleRequest) GetStreamId() []byte {
if x != nil {
return x.StreamId
}
return nil
}
func (x *SampleRequest) GetBatchHeaderHash() []byte {
if x != nil {
return x.BatchHeaderHash
}
return nil
}
func (x *SampleRequest) GetBlobIndex() uint32 {
if x != nil {
return x.BlobIndex
}
return 0
}
func (x *SampleRequest) GetTimes() uint32 {
if x != nil {
return x.Times
}
return 0
}
// SampleReply contains the sample result
type SampleReply struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"`
}
func (x *SampleReply) Reset() {
*x = SampleReply{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SampleReply) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SampleReply) ProtoMessage() {}
func (x *SampleReply) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SampleReply.ProtoReflect.Descriptor instead.
func (*SampleReply) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{1}
}
func (x *SampleReply) GetSuccess() bool {
if x != nil {
return x.Success
}
return false
}
type RetrieveRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
BatchHeaderHash []byte `protobuf:"bytes,1,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"`
BlobIndex uint32 `protobuf:"varint,2,opt,name=blob_index,json=blobIndex,proto3" json:"blob_index,omitempty"`
}
func (x *RetrieveRequest) Reset() {
*x = RetrieveRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RetrieveRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RetrieveRequest) ProtoMessage() {}
func (x *RetrieveRequest) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RetrieveRequest.ProtoReflect.Descriptor instead.
func (*RetrieveRequest) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{2}
}
func (x *RetrieveRequest) GetBatchHeaderHash() []byte {
if x != nil {
return x.BatchHeaderHash
}
return nil
}
func (x *RetrieveRequest) GetBlobIndex() uint32 {
if x != nil {
return x.BlobIndex
}
return 0
}
type RetrieveReply struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Status bool `protobuf:"varint,1,opt,name=status,proto3" json:"status,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
}
func (x *RetrieveReply) Reset() {
*x = RetrieveReply{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RetrieveReply) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RetrieveReply) ProtoMessage() {}
func (x *RetrieveReply) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RetrieveReply.ProtoReflect.Descriptor instead.
func (*RetrieveReply) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{3}
}
func (x *RetrieveReply) GetStatus() bool {
if x != nil {
return x.Status
}
return false
}
func (x *RetrieveReply) GetData() []byte {
if x != nil {
return x.Data
}
return nil
}
var File_light_light_proto protoreflect.FileDescriptor
var file_light_light_proto_rawDesc = []byte{
0x0a, 0x11, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2f, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x12, 0x05, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x22, 0x8d, 0x01, 0x0a, 0x0d, 0x53,
0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09,
0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52,
0x08, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x49, 0x64, 0x12, 0x2a, 0x0a, 0x11, 0x62, 0x61, 0x74,
0x63, 0x68, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02,
0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65,
0x72, 0x48, 0x61, 0x73, 0x68, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x62, 0x5f, 0x69, 0x6e,
0x64, 0x65, 0x78, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x62, 0x49,
0x6e, 0x64, 0x65, 0x78, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x18, 0x04, 0x20,
0x01, 0x28, 0x0d, 0x52, 0x05, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x22, 0x27, 0x0a, 0x0b, 0x53, 0x61,
0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x63,
0x63, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75, 0x63, 0x63,
0x65, 0x73, 0x73, 0x22, 0x5c, 0x0a, 0x0f, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2a, 0x0a, 0x11, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f,
0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28,
0x0c, 0x52, 0x0f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x48, 0x61,
0x73, 0x68, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x62, 0x5f, 0x69, 0x6e, 0x64, 0x65, 0x78,
0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x62, 0x49, 0x6e, 0x64, 0x65,
0x78, 0x22, 0x3b, 0x0a, 0x0d, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, 0x65, 0x70,
0x6c, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01,
0x28, 0x08, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61,
0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x79,
0x0a, 0x05, 0x4c, 0x69, 0x67, 0x68, 0x74, 0x12, 0x34, 0x0a, 0x06, 0x53, 0x61, 0x6d, 0x70, 0x6c,
0x65, 0x12, 0x14, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x12, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e,
0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x12, 0x3a, 0x0a,
0x08, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x12, 0x16, 0x2e, 0x6c, 0x69, 0x67, 0x68,
0x74, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x1a, 0x14, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65,
0x76, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x42, 0x30, 0x5a, 0x2e, 0x67, 0x69, 0x74,
0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x30, 0x67, 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x30,
0x67, 0x2d, 0x64, 0x61, 0x74, 0x61, 0x2d, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x2f, 0x72, 0x75, 0x6e,
0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x33,
}
var (
file_light_light_proto_rawDescOnce sync.Once
file_light_light_proto_rawDescData = file_light_light_proto_rawDesc
)
func file_light_light_proto_rawDescGZIP() []byte {
file_light_light_proto_rawDescOnce.Do(func() {
file_light_light_proto_rawDescData = protoimpl.X.CompressGZIP(file_light_light_proto_rawDescData)
})
return file_light_light_proto_rawDescData
}
var file_light_light_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_light_light_proto_goTypes = []interface{}{
(*SampleRequest)(nil), // 0: light.SampleRequest
(*SampleReply)(nil), // 1: light.SampleReply
(*RetrieveRequest)(nil), // 2: light.RetrieveRequest
(*RetrieveReply)(nil), // 3: light.RetrieveReply
}
var file_light_light_proto_depIdxs = []int32{
0, // 0: light.Light.Sample:input_type -> light.SampleRequest
2, // 1: light.Light.Retrieve:input_type -> light.RetrieveRequest
1, // 2: light.Light.Sample:output_type -> light.SampleReply
3, // 3: light.Light.Retrieve:output_type -> light.RetrieveReply
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_light_light_proto_init() }
func file_light_light_proto_init() {
if File_light_light_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_light_light_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SampleRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SampleReply); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RetrieveRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RetrieveReply); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_light_light_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_light_light_proto_goTypes,
DependencyIndexes: file_light_light_proto_depIdxs,
MessageInfos: file_light_light_proto_msgTypes,
}.Build()
File_light_light_proto = out.File
file_light_light_proto_rawDesc = nil
file_light_light_proto_goTypes = nil
file_light_light_proto_depIdxs = nil
}

View File

@ -0,0 +1,141 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v4.25.3
// source: light/light.proto
package light
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// LightClient is the client API for Light service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type LightClient interface {
Sample(ctx context.Context, in *SampleRequest, opts ...grpc.CallOption) (*SampleReply, error)
Retrieve(ctx context.Context, in *RetrieveRequest, opts ...grpc.CallOption) (*RetrieveReply, error)
}
type lightClient struct {
cc grpc.ClientConnInterface
}
func NewLightClient(cc grpc.ClientConnInterface) LightClient {
return &lightClient{cc}
}
func (c *lightClient) Sample(ctx context.Context, in *SampleRequest, opts ...grpc.CallOption) (*SampleReply, error) {
out := new(SampleReply)
err := c.cc.Invoke(ctx, "/light.Light/Sample", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *lightClient) Retrieve(ctx context.Context, in *RetrieveRequest, opts ...grpc.CallOption) (*RetrieveReply, error) {
out := new(RetrieveReply)
err := c.cc.Invoke(ctx, "/light.Light/Retrieve", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// LightServer is the server API for Light service.
// All implementations must embed UnimplementedLightServer
// for forward compatibility
type LightServer interface {
Sample(context.Context, *SampleRequest) (*SampleReply, error)
Retrieve(context.Context, *RetrieveRequest) (*RetrieveReply, error)
mustEmbedUnimplementedLightServer()
}
// UnimplementedLightServer must be embedded to have forward compatible implementations.
type UnimplementedLightServer struct {
}
func (UnimplementedLightServer) Sample(context.Context, *SampleRequest) (*SampleReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method Sample not implemented")
}
func (UnimplementedLightServer) Retrieve(context.Context, *RetrieveRequest) (*RetrieveReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method Retrieve not implemented")
}
func (UnimplementedLightServer) mustEmbedUnimplementedLightServer() {}
// UnsafeLightServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to LightServer will
// result in compilation errors.
type UnsafeLightServer interface {
mustEmbedUnimplementedLightServer()
}
func RegisterLightServer(s grpc.ServiceRegistrar, srv LightServer) {
s.RegisterService(&Light_ServiceDesc, srv)
}
func _Light_Sample_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SampleRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LightServer).Sample(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/light.Light/Sample",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LightServer).Sample(ctx, req.(*SampleRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Light_Retrieve_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RetrieveRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LightServer).Retrieve(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/light.Light/Retrieve",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LightServer).Retrieve(ctx, req.(*RetrieveRequest))
}
return interceptor(ctx, in, info, handler)
}
// Light_ServiceDesc is the grpc.ServiceDesc for Light service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Light_ServiceDesc = grpc.ServiceDesc{
ServiceName: "light.Light",
HandlerType: (*LightServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Sample",
Handler: _Light_Sample_Handler,
},
{
MethodName: "Retrieve",
Handler: _Light_Retrieve_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "light/light.proto",
}

89
helper/da/main.go Normal file
View File

@ -0,0 +1,89 @@
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/0glabs/0g-evmos/helper/da/service"
"github.com/0glabs/0g-evmos/helper/da/types"
"github.com/lesismal/nbio/nbhttp"
"github.com/lesismal/nbio/nbhttp/websocket"
)
const (
subscribeMsg = "{\"jsonrpc\":\"2.0\",\"method\":\"subscribe\",\"id\":1,\"params\":{\"query\":\"tm.event='Tx'\"}}"
)
var (
rpcAddress = flag.String("rpc-address", "34.214.2.28:32001", "address of da-light rpc server")
wsAddress = flag.String("ws-address", "127.0.0.1:26657", "address of emvos ws server")
relativePath = flag.String("relative-path", "", "relative path of evmosd")
account = flag.String("account", "", "account to run evmosd cli")
keyring = flag.String("keyring", "", "keyring to run evmosd cli")
homePath = flag.String("home", "", "home path of evmosd node")
)
func newUpgrader() *websocket.Upgrader {
u := websocket.NewUpgrader()
u.OnMessage(func(c *websocket.Conn, messageType websocket.MessageType, data []byte) {
log.Println("onEcho:", string(data))
ctx := context.WithValue(context.Background(), types.DA_RPC_ADDRESS, *rpcAddress)
ctx = context.WithValue(ctx, types.NODE_CLI_RELATIVE_PATH, *relativePath)
ctx = context.WithValue(ctx, types.NODE_CLI_EXEC_ACCOUNT, *account)
ctx = context.WithValue(ctx, types.NODE_CLI_EXEC_KEYRING, *keyring)
ctx = context.WithValue(ctx, types.NODE_HOME_PATH, *homePath)
go func() { service.OnMessage(ctx, c, messageType, data) }()
})
u.OnClose(func(c *websocket.Conn, err error) {
fmt.Println("OnClose:", c.RemoteAddr().String(), err)
service.OnClose()
})
return u
}
func main() {
flag.Parse()
engine := nbhttp.NewEngine(nbhttp.Config{})
err := engine.Start()
if err != nil {
fmt.Printf("nbio.Start failed: %v\n", err)
return
}
go func() {
u := url.URL{Scheme: "ws", Host: *wsAddress, Path: "/websocket"}
dialer := &websocket.Dialer{
Engine: engine,
Upgrader: newUpgrader(),
DialTimeout: time.Second * 3,
}
c, res, err := dialer.Dial(u.String(), nil)
if err != nil {
if res != nil && res.Body != nil {
bReason, _ := io.ReadAll(res.Body)
fmt.Printf("dial failed: %v, reason: %v\n", err, string(bReason))
} else {
fmt.Printf("dial failed: %v\n", err)
}
return
}
c.WriteMessage(websocket.TextMessage, []byte(subscribeMsg))
}()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
<-interrupt
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
engine.Shutdown(ctx)
}

View File

@ -0,0 +1,33 @@
syntax = "proto3";
package light;
option go_package = "proto/light";
service Light {
rpc Sample(SampleRequest) returns (SampleReply) {}
rpc Retrieve(RetrieveRequest) returns (RetrieveReply) {}
}
// SampleRequest contains the blob to sample (by batch and blob index) and required sample times
message SampleRequest {
bytes stream_id = 1;
bytes batch_header_hash = 2;
uint32 blob_index = 3;
uint32 times = 4;
}
// SampleReply contains the sample result
message SampleReply {
bool success = 1;
}
message RetrieveRequest {
bytes batch_header_hash = 1;
uint32 blob_index = 2;
}
message RetrieveReply {
bool status = 1;
bytes data = 2;
}

View File

@ -0,0 +1,186 @@
package service
import (
"context"
"encoding/hex"
"os"
"os/exec"
"strconv"
"strings"
"github.com/0glabs/0g-evmos/helper/da/client"
"github.com/0glabs/0g-evmos/helper/da/types"
"github.com/0glabs/0g-evmos/helper/da/utils/sizedw8grp"
jsoniter "github.com/json-iterator/go"
"github.com/lesismal/nbio/nbhttp/websocket"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
const (
defaultClientInstance = 10
)
var rpcClient client.DaLightRpcClient
func OnMessage(ctx context.Context, c *websocket.Conn, messageType websocket.MessageType, data []byte) {
if messageType == websocket.TextMessage {
rawMsg := unwrapJsonRpc(data)
if verifyQuery(rawMsg) {
eventStr := jsoniter.Get(rawMsg, "events").ToString()
events := map[string][]string{}
if err := jsoniter.UnmarshalFromString(eventStr, &events); err == nil {
dasRequestMap := make(map[string]string, 4)
for key, val := range events {
if strings.HasPrefix(key, "das_request.") {
dasRequestMap[strings.ReplaceAll(key, "das_request.", "")] = val[0]
}
}
if len(dasRequestMap) == 4 {
rid, _ := strconv.ParseUint(dasRequestMap["request_id"], 10, 64)
numBlobs, _ := strconv.ParseUint(dasRequestMap["num_blobs"], 10, 64)
req := types.DASRequest{
RequestId: rid,
StreamId: dasRequestMap["stream_id"],
BatchHeaderHash: dasRequestMap["batch_header_hash"],
NumBlobs: numBlobs,
}
err := handleDasRequest(ctx, req)
if err != nil {
log.Err(err).Msgf("failed to handle das request: %v, %v", req, err)
} else {
log.Info().Msgf("successfully handled das request: %v", req)
}
}
}
}
} else {
// TODO: handle other message
}
}
func OnClose() {
if rpcClient != nil {
rpcClient.Destroy()
rpcClient = nil
}
}
func unwrapJsonRpc(data []byte) []byte {
result := jsoniter.Get(data, "result")
if 0 < len(result.Keys()) {
return []byte(result.ToString())
}
return []byte{}
}
func verifyQuery(data []byte) bool {
if len(data) > 0 {
return jsoniter.Get(data, "query").ToString() == "tm.event='Tx'"
}
return false
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func handleDasRequest(ctx context.Context, request types.DASRequest) error {
if rpcClient == nil {
addrVal := ctx.Value(types.DA_RPC_ADDRESS)
if addrVal == nil {
return errors.New("da light service address not found in context")
}
limit := ctx.Value(types.INSTANCE_LIMIT)
if limit == nil {
limit = defaultClientInstance
}
rpcClient = client.NewDaLightClient(addrVal.(string), limit.(int))
}
streamID, err := hex.DecodeString(request.StreamId)
if err != nil {
return err
}
batchHeaderHash, err := hex.DecodeString(request.BatchHeaderHash)
if err != nil {
return err
}
result := make(chan bool, request.NumBlobs)
taskCnt := min(rpcClient.GetInstanceCount(), int(request.NumBlobs))
wg := sizedw8grp.New(taskCnt)
for i := uint64(0); i < request.NumBlobs; i++ {
wg.Add()
go func(idx uint64) {
defer wg.Done()
ret, err := rpcClient.Sample(ctx, streamID, batchHeaderHash, uint32(idx), 1)
if err != nil {
log.Err(err).Msgf("failed to sample data availability with blob index %d", idx)
result <- false
} else {
log.Info().Msgf("sample result for blob index %d: %v", idx, ret)
result <- ret
}
}(i)
}
wg.Wait()
close(result)
finalResult := true
for val := range result {
if !val {
finalResult = false
break
}
}
return runEvmosdCliReportDasResult(ctx, request.RequestId, finalResult)
}
func runEvmosdCliReportDasResult(ctx context.Context, requestId uint64, result bool) error {
relativePath := ctx.Value(types.NODE_CLI_RELATIVE_PATH)
if relativePath == nil {
return errors.New("relativePath not found in context")
}
account := ctx.Value(types.NODE_CLI_EXEC_ACCOUNT)
if account == nil {
return errors.New("account not found in context")
}
args := []string{
"tx",
"das",
"report-das-result",
strconv.FormatUint(requestId, 10),
strconv.FormatBool(result),
"--from", account.(string),
"--gas-prices", "767812500aevmos", // TODO: use args to set gas prices
}
homePath := ctx.Value(types.NODE_HOME_PATH)
if homePath != nil {
args = append(args, "--home", homePath.(string))
}
keyring := ctx.Value(types.NODE_CLI_EXEC_KEYRING)
if keyring != nil {
args = append(args, "--keyring-backend", keyring.(string))
}
cmdStr := relativePath.(string) + "evmosd"
cmd := exec.Command(cmdStr, append(args, "-y")...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

View File

@ -0,0 +1,8 @@
package types
type DASRequest struct {
RequestId uint64 `json:"request_id"`
StreamId string `json:"stream_id"`
BatchHeaderHash string `json:"batch_header_hash"`
NumBlobs uint64 `json:"num_blobs"`
}

10
helper/da/types/keys.go Normal file
View File

@ -0,0 +1,10 @@
package types
const (
DA_RPC_ADDRESS = "rpc_address"
INSTANCE_LIMIT = "instance_limit"
NODE_CLI_RELATIVE_PATH = "relative_path"
NODE_CLI_EXEC_ACCOUNT = "node_exec_account"
NODE_CLI_EXEC_KEYRING = "node_exec_keyring"
NODE_HOME_PATH = "home_path"
)

View File

@ -0,0 +1,51 @@
package sizedw8grp
import (
"context"
"math"
"sync"
)
type SizedWaitGroup struct {
Size int
current chan struct{}
wg sync.WaitGroup
}
func New(limit int) SizedWaitGroup {
size := math.MaxInt32
if limit > 0 {
size = limit
}
return SizedWaitGroup{
Size: size,
current: make(chan struct{}, size),
wg: sync.WaitGroup{},
}
}
func (s *SizedWaitGroup) Add() {
_ = s.AddWithContext(context.Background())
}
func (s *SizedWaitGroup) AddWithContext(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case s.current <- struct{}{}:
break
}
s.wg.Add(1)
return nil
}
func (s *SizedWaitGroup) Done() {
<-s.current
s.wg.Done()
}
func (s *SizedWaitGroup) Wait() {
s.wg.Wait()
}

View File

@ -5,7 +5,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
// communitytypes "github.com/kava-labs/kava/x/community/types" // communitytypes "github.com/0glabs/0g-chain/x/community/types"
) )
// func (suite *IntegrationTestSuite) TestCommunityUpdateParams_NonAuthority() { // func (suite *IntegrationTestSuite) TestCommunityUpdateParams_NonAuthority() {

View File

@ -12,9 +12,9 @@ import (
ethtypes "github.com/ethereum/go-ethereum/core/types" ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/kava-labs/kava/tests/e2e/testutil" "github.com/0glabs/0g-chain/tests/e2e/testutil"
"github.com/kava-labs/kava/tests/util" "github.com/0glabs/0g-chain/tests/util"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
) )
const initialCosmosCoinConversionDenomFunds = int64(1e4) const initialCosmosCoinConversionDenomFunds = int64(1e4)

View File

@ -10,12 +10,12 @@ import (
txtypes "github.com/cosmos/cosmos-sdk/types/tx" txtypes "github.com/cosmos/cosmos-sdk/types/tx"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
// cdptypes "github.com/kava-labs/kava/x/cdp/types" // cdptypes "github.com/0glabs/0g-chain/x/cdp/types"
// evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" // evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
"github.com/kava-labs/kava/tests/e2e/contracts/greeter" "github.com/0glabs/0g-chain/tests/e2e/contracts/greeter"
"github.com/kava-labs/kava/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
func (suite *IntegrationTestSuite) TestEthCallToGreeterContract() { func (suite *IntegrationTestSuite) TestEthCallToGreeterContract() {

View File

@ -6,7 +6,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
) )
func (suite *IntegrationTestSuite) TestGrpcClientQueryCosmosModule_Balance() { func (suite *IntegrationTestSuite) TestGrpcClientQueryCosmosModule_Balance() {

View File

@ -12,8 +12,8 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
ethtypes "github.com/ethereum/go-ethereum/core/types" ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
func (suite *IntegrationTestSuite) TestEthGasPriceReturnsMinFee() { func (suite *IntegrationTestSuite) TestEthGasPriceReturnsMinFee() {

View File

@ -18,9 +18,9 @@ import (
ethtypes "github.com/ethereum/go-ethereum/core/types" ethtypes "github.com/ethereum/go-ethereum/core/types"
emtypes "github.com/evmos/ethermint/types" emtypes "github.com/evmos/ethermint/types"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/tests/e2e/testutil" "github.com/0glabs/0g-chain/tests/e2e/testutil"
"github.com/kava-labs/kava/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
var ( var (

View File

@ -7,7 +7,7 @@ import (
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice" "github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/kava-labs/kava/client/grpc" "github.com/0glabs/0g-chain/client/grpc"
) )
// LiveNodeRunnerConfig implements NodeRunner. // LiveNodeRunnerConfig implements NodeRunner.

View File

@ -28,8 +28,8 @@ import (
emtests "github.com/evmos/ethermint/tests" emtests "github.com/evmos/ethermint/tests"
emtypes "github.com/evmos/ethermint/types" emtypes "github.com/evmos/ethermint/types"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
// SigningAccount wraps details about an account and its private keys. // SigningAccount wraps details about an account and its private keys.

View File

@ -21,11 +21,11 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/ethclient"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
kavaparams "github.com/kava-labs/kava/app/params" kavaparams "github.com/0glabs/0g-chain/app/params"
"github.com/kava-labs/kava/client/grpc" "github.com/0glabs/0g-chain/client/grpc"
"github.com/kava-labs/kava/tests/e2e/runner" "github.com/0glabs/0g-chain/tests/e2e/runner"
"github.com/kava-labs/kava/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
// Chain wraps query clients & accounts for a network // Chain wraps query clients & accounts for a network

View File

@ -27,7 +27,7 @@ type SuiteConfig struct {
IncludeIbcTests bool IncludeIbcTests bool
// The contract address of a deployed ERC-20 token // The contract address of a deployed ERC-20 token
KavaErc20Address string ZgchainERC20Address string
// When true, the chains will remain running after tests complete (pass or fail) // When true, the chains will remain running after tests complete (pass or fail)
SkipShutdown bool SkipShutdown bool
@ -66,7 +66,7 @@ func ParseSuiteConfig() SuiteConfig {
// this mnemonic is expected to be a funded account that can seed the funds for all // this mnemonic is expected to be a funded account that can seed the funds for all
// new accounts created during tests. it will be available under Accounts["whale"] // new accounts created during tests. it will be available under Accounts["whale"]
FundedAccountMnemonic: nonemptyStringEnv("E2E_KAVA_FUNDED_ACCOUNT_MNEMONIC"), FundedAccountMnemonic: nonemptyStringEnv("E2E_KAVA_FUNDED_ACCOUNT_MNEMONIC"),
KavaErc20Address: nonemptyStringEnv("E2E_KAVA_ERC20_ADDRESS"), ZgchainERC20Address: nonemptyStringEnv("E2E_KAVA_ERC20_ADDRESS"),
IncludeIbcTests: mustParseBool("E2E_INCLUDE_IBC_TESTS"), IncludeIbcTests: mustParseBool("E2E_INCLUDE_IBC_TESTS"),
} }

View File

@ -7,9 +7,9 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/kava-labs/kava/tests/e2e/contracts/greeter" "github.com/0glabs/0g-chain/tests/e2e/contracts/greeter"
// "github.com/kava-labs/kava/x/cdp/types" // "github.com/0glabs/0g-chain/x/cdp/types"
evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
) )
// InitKavaEvmData is run after the chain is running, but before the tests are run. // InitKavaEvmData is run after the chain is running, but before the tests are run.
@ -35,7 +35,7 @@ func (suite *E2eTestSuite) InitKavaEvmData() {
found := false found := false
erc20Addr := suite.DeployedErc20.Address.Hex() erc20Addr := suite.DeployedErc20.Address.Hex()
for _, p := range params.Params.EnabledConversionPairs { for _, p := range params.Params.EnabledConversionPairs {
if common.BytesToAddress(p.KavaERC20Address).Hex() == erc20Addr { if common.BytesToAddress(p.ZgchainERC20Address).Hex() == erc20Addr {
found = true found = true
suite.DeployedErc20.CosmosDenom = p.Denom suite.DeployedErc20.CosmosDenom = p.Denom
} }

View File

@ -10,9 +10,9 @@ import (
sdkmath "cosmossdk.io/math" sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/tests/e2e/runner" "github.com/0glabs/0g-chain/tests/e2e/runner"
"github.com/kava-labs/kava/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
const ( const (
@ -27,7 +27,7 @@ const (
) )
// DeployedErc20 is a type that wraps the details of the pre-deployed erc20 used by the e2e test suite. // DeployedErc20 is a type that wraps the details of the pre-deployed erc20 used by the e2e test suite.
// The Address comes from SuiteConfig.KavaErc20Address // The Address comes from SuiteConfig.ZgchainERC20Address
// The CosmosDenom is fetched from the EnabledConversionPairs param of x/evmutil. // The CosmosDenom is fetched from the EnabledConversionPairs param of x/evmutil.
// The tests expect the following: // The tests expect the following:
// - the funded account has a nonzero balance of the erc20 // - the funded account has a nonzero balance of the erc20
@ -90,7 +90,7 @@ func (suite *E2eTestSuite) SetupSuite() {
suiteConfig := ParseSuiteConfig() suiteConfig := ParseSuiteConfig()
suite.config = suiteConfig suite.config = suiteConfig
suite.DeployedErc20 = DeployedErc20{ suite.DeployedErc20 = DeployedErc20{
Address: common.HexToAddress(suiteConfig.KavaErc20Address), Address: common.HexToAddress(suiteConfig.ZgchainERC20Address),
// Denom & CdpCollateralType are fetched in InitKavaEvmData() // Denom & CdpCollateralType are fetched in InitKavaEvmData()
} }

View File

@ -8,8 +8,8 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/kava-labs/kava/app" "github.com/0glabs/0g-chain/app"
"github.com/kava-labs/kava/tests/util" "github.com/0glabs/0g-chain/tests/util"
) )
func TestAddressConversion(t *testing.T) { func TestAddressConversion(t *testing.T) {

View File

@ -6,7 +6,7 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/kava-labs/kava/app/params" "github.com/0glabs/0g-chain/app/params"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
grpcstatus "google.golang.org/grpc/status" grpcstatus "google.golang.org/grpc/status"

View File

@ -0,0 +1,87 @@
package cli
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/0glabs/0g-chain/x/committee/v1/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
)
// GetQueryCmd returns the cli query commands for the inflation module.
func GetQueryCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: "Querying commands for the committee module",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
GetCurrentCommitteeID(),
GetRegisteredVoters(),
)
return cmd
}
func GetCurrentCommitteeID() *cobra.Command {
cmd := &cobra.Command{
Use: "current-committee-id",
Short: "Query the current committee ID",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
params := &types.QueryCurrentCommitteeIDRequest{}
res, err := queryClient.CurrentCommitteeID(context.Background(), params)
if err != nil {
return err
}
return clientCtx.PrintString(fmt.Sprintf("%v\n", res.CurrentCommitteeID))
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func GetRegisteredVoters() *cobra.Command {
cmd := &cobra.Command{
Use: "registered-voters",
Short: "Query registered voters",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
params := &types.QueryRegisteredVotersRequest{}
res, err := queryClient.RegisteredVoters(context.Background(), params)
if err != nil {
return err
}
return clientCtx.PrintString(fmt.Sprintf("%v\n", strings.Join(res.Voters, ",")))
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}

View File

@ -0,0 +1,196 @@
package cli
import (
"bufio"
"bytes"
"encoding/hex"
"errors"
"fmt"
"strconv"
sdkmath "cosmossdk.io/math"
"github.com/0glabs/0g-chain/crypto/vrf"
"github.com/0glabs/0g-chain/x/committee/v1/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdkkr "github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
vrfalgo "github.com/coniks-sys/coniks-go/crypto/vrf"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/spf13/cobra"
)
// GetTxCmd returns the transaction commands for this module
func GetTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName),
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
NewRegisterCmd(),
NewVoteCmd(),
)
return cmd
}
func NewRegisterCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "register",
Short: "Register a voter",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
// bypass the restriction of set keyring options
ctx := client.GetClientContextFromCmd(cmd).WithKeyringOptions(vrf.VrfOption())
client.SetCmdClientContext(cmd, ctx)
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
kr := clientCtx.Keyring
// get account name by address
accAddr := clientCtx.GetFromAddress()
accRecord, err := kr.KeyByAddress(accAddr)
if err != nil {
// not found record by address in keyring
return nil
}
// check voter account record exists
voterAccName := accRecord.Name + "-voter"
_, err = kr.Key(voterAccName)
if err == nil {
// account exists, ask for user confirmation
response, err2 := input.GetConfirmation(fmt.Sprintf("override the existing name %s", voterAccName), bufio.NewReader(clientCtx.Input), cmd.ErrOrStderr())
if err2 != nil {
return err2
}
if !response {
return errors.New("aborted")
}
err2 = kr.Delete(voterAccName)
if err2 != nil {
return err2
}
}
keyringAlgos, _ := kr.SupportedAlgorithms()
algo, err := sdkkr.NewSigningAlgoFromString("vrf", keyringAlgos)
if err != nil {
return err
}
newRecord, err := kr.NewAccount(voterAccName, "", "", "", algo)
if err != nil {
return err
}
pubKey, err := newRecord.GetPubKey()
if err != nil {
return err
}
valAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(clientCtx.GetFromAddress().Bytes()))
if err != nil {
return err
}
msg := &types.MsgRegister{
Voter: valAddr.String(),
Key: pubKey.Bytes(),
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func NewVoteCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "vote committee-id",
Short: "Vote on a proposal",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
kr := clientCtx.Keyring
// get account name by address
inAddr := clientCtx.GetFromAddress()
valAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(inAddr.Bytes()))
if err != nil {
return err
}
inRecord, err := kr.KeyByAddress(inAddr)
if err != nil {
// not found record by address in keyring
return nil
}
// check voter account record exists
voterAccName := inRecord.Name + "-voter"
voterRecord, err := kr.Key(voterAccName)
if err != nil {
// not found voter account
return err
}
sk := vrfalgo.PrivateKey(voterRecord.GetLocal().PrivKey.Value)
committeeID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
votingStartHeight := types.DefaultVotingStartHeight + (committeeID-1)*types.DefaultVotingPeriod
rsp, err := stakingtypes.NewQueryClient(clientCtx).HistoricalInfo(cmd.Context(), &stakingtypes.QueryHistoricalInfoRequest{Height: int64(votingStartHeight)})
if err != nil {
return err
}
var tokens sdkmath.Int
for _, val := range rsp.Hist.Valset {
thisValAddr := val.GetOperator()
if thisValAddr.Equals(valAddr) {
tokens = val.GetTokens()
}
}
// 1_000 0AGI token / vote
numBallots := tokens.Quo(sdk.NewInt(1_000_000_000_000_000_000)).Quo(sdk.NewInt(1_000)).Uint64()
ballots := make([]*types.Ballot, numBallots)
for i := range ballots {
ballotID := uint64(i)
ballots[i] = &types.Ballot{
ID: ballotID,
Content: sk.Compute(bytes.Join([][]byte{rsp.Hist.Header.LastCommitHash, types.Uint64ToBytes(ballotID)}, nil)),
}
}
msg := &types.MsgVote{
CommitteeID: committeeID,
Voter: valAddr.String(),
Ballots: ballots,
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}

56
x/committee/v1/genesis.go Normal file
View File

@ -0,0 +1,56 @@
package committee
import (
"fmt"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/0glabs/0g-chain/x/committee/v1/keeper"
"github.com/0glabs/0g-chain/x/committee/v1/types"
)
// InitGenesis initializes the store state from a genesis state.
func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, gs types.GenesisState) {
if err := gs.Validate(); err != nil {
panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err))
}
params := gs.Params
err := keeper.SetParams(ctx, params)
if err != nil {
panic(errorsmod.Wrapf(err, "error setting params"))
}
keeper.SetCurrentCommitteeID(ctx, gs.CurrentCommitteeID)
for _, p := range gs.Committees {
keeper.SetCommittee(ctx, p)
}
}
// ExportGenesis returns a GenesisState for a given context and keeper.
func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState {
startHeight, err := keeper.GetVotingStartHeight(ctx)
if err != nil {
panic(err)
}
period, err := keeper.GetVotingPeriod(ctx)
if err != nil {
panic(err)
}
currentID, err := keeper.GetCurrentCommitteeID(ctx)
if err != nil {
panic(err)
}
return types.NewGenesisState(
keeper.GetParams(ctx),
startHeight,
period,
currentID,
keeper.GetCommittees(ctx),
)
}

View File

@ -0,0 +1,72 @@
package keeper
import (
"sort"
abci "github.com/cometbft/cometbft/abci/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
type Ballot struct {
voter sdk.ValAddress
content string
}
func (k *Keeper) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) {
committeeID, err := k.GetCurrentCommitteeID(ctx)
if err != nil {
// TODO: handle the case where committeeID is not available
return
}
committee, bz := k.GetCommittee(ctx, committeeID)
if !bz {
return
}
if ctx.BlockHeight() >= int64(committee.StartHeight) {
// We are ready to accept votes for the next committee
if err := k.StoreNewCommittee(ctx, committee.StartHeight); err != nil {
return
}
}
if ctx.BlockHeight() < int64(committee.EndHeight) {
return
}
k.IncrementCurrentCommitteeID(ctx)
committee, bz = k.GetCommittee(ctx, committeeID+1)
if !bz {
return
}
ballots := []Ballot{}
seen := make(map[string]struct{})
for _, vote := range committee.Votes {
for _, ballot := range vote.Ballots {
ballot := Ballot{
voter: vote.Voter,
content: string(ballot.Content),
}
if _, ok := seen[ballot.content]; ok {
continue
}
ballots = append(ballots, ballot)
seen[ballot.content] = struct{}{}
}
}
sort.Slice(ballots, func(i, j int) bool {
return ballots[i].content < ballots[j].content
})
committeeSize := k.GetParams(ctx).CommitteeSize
committee.Members = make([]sdk.ValAddress, committeeSize)
for i := 0; i < int(committeeSize); i = i + 1 {
committee.Members[i] = ballots[i].voter
}
k.SetCommittee(ctx, committee)
}
func (k *Keeper) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) {
}

View File

@ -0,0 +1,35 @@
package keeper
import (
"context"
"github.com/0glabs/0g-chain/x/committee/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var _ types.QueryServer = Keeper{}
func (k Keeper) CurrentCommitteeID(
c context.Context,
_ *types.QueryCurrentCommitteeIDRequest,
) (*types.QueryCurrentCommitteeIDResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
currentCommitteeID, err := k.GetCurrentCommitteeID(ctx)
if err != nil {
return nil, err
}
return &types.QueryCurrentCommitteeIDResponse{CurrentCommitteeID: currentCommitteeID}, nil
}
func (k Keeper) RegisteredVoters(
c context.Context,
_ *types.QueryRegisteredVotersRequest,
) (*types.QueryRegisteredVotersResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
voterAddrs := k.GetVoters(ctx)
voters := make([]string, len(voterAddrs))
for i, voterAddr := range voterAddrs {
voters[i] = voterAddr.String()
}
return &types.QueryRegisteredVotersResponse{Voters: voters}, nil
}

View File

@ -0,0 +1,323 @@
package keeper
import (
"fmt"
errorsmod "cosmossdk.io/errors"
"github.com/cometbft/cometbft/libs/log"
"github.com/coniks-sys/coniks-go/crypto/vrf"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/0glabs/0g-chain/x/committee/v1/types"
)
// Keeper of the inflation store
type Keeper struct {
storeKey storetypes.StoreKey
cdc codec.BinaryCodec
stakingKeeper types.StakingKeeper
}
// NewKeeper creates a new mint Keeper instance
func NewKeeper(
storeKey storetypes.StoreKey,
cdc codec.BinaryCodec,
stakingKeeper types.StakingKeeper,
) Keeper {
return Keeper{
storeKey: storeKey,
cdc: cdc,
stakingKeeper: stakingKeeper,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
// ------------------------------------------
// Committees
// ------------------------------------------
func (k Keeper) SetCurrentCommitteeID(ctx sdk.Context, id uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.CurrentCommitteeIDKey, types.GetKeyFromID(id))
}
func (k Keeper) GetCurrentCommitteeID(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.CurrentCommitteeIDKey)
if bz == nil {
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "current committee ID not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}
func (k Keeper) IncrementCurrentCommitteeID(ctx sdk.Context) error {
id, err := k.GetCurrentCommitteeID(ctx)
if err != nil {
return err
}
k.SetCurrentCommitteeID(ctx, id+1)
return nil
}
func (k Keeper) SetVotingStartHeight(ctx sdk.Context, votingStartHeight uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.VotingStartHeightKey, types.GetKeyFromID(votingStartHeight))
}
func (k Keeper) GetVotingStartHeight(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.VotingStartHeightKey)
if bz == nil {
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "voting start height not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}
func (k Keeper) SetVotingPeriod(ctx sdk.Context, votingPeriod uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.VotingPeriodKey, types.GetKeyFromID(votingPeriod))
}
func (k Keeper) GetVotingPeriod(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.VotingPeriodKey)
if bz == nil {
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "voting period not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}
// StoreNewCommittee stores a committee, adding a new ID
func (k Keeper) StoreNewCommittee(ctx sdk.Context, votingStartHeight uint64) error {
currentCommitteeID, err := k.GetCurrentCommitteeID(ctx)
if err != nil {
return err
}
votingPeriod, err := k.GetVotingPeriod(ctx)
if err != nil {
return err
}
com := types.Committee{
ID: currentCommitteeID + 1,
VotingStartHeight: votingStartHeight,
StartHeight: votingStartHeight + votingPeriod,
EndHeight: votingStartHeight + votingPeriod*2,
Votes: []types.Vote{},
Members: []sdk.ValAddress{},
}
k.SetCommittee(ctx, com)
return nil
}
func (k Keeper) GetCommittee(ctx sdk.Context, committeeID uint64) (types.Committee, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix)
bz := store.Get(types.GetKeyFromID(committeeID))
if bz == nil {
return types.Committee{}, false
}
var com types.Committee
k.cdc.MustUnmarshal(bz, &com)
return com, true
}
// SetCommittee puts a committee into the store.
func (k Keeper) SetCommittee(ctx sdk.Context, committee types.Committee) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix)
bz := k.cdc.MustMarshal(&committee)
store.Set(types.GetKeyFromID(committee.ID), bz)
}
// // DeleteProposal removes a proposal from the store.
// func (k Keeper) DeleteProposal(ctx sdk.Context, proposalID uint64) {
// store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ProposalKeyPrefix)
// store.Delete(types.GetKeyFromID(proposalID))
// }
// IterateProposals provides an iterator over all stored proposals.
// For each proposal, cb will be called. If cb returns true, the iterator will close and stop.
func (k Keeper) IterateCommittee(ctx sdk.Context, cb func(proposal types.Committee) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var committee types.Committee
k.cdc.MustUnmarshal(iterator.Value(), &committee)
if cb(committee) {
break
}
}
}
func (k Keeper) GetCommittees(ctx sdk.Context) types.Committees {
results := types.Committees{}
k.IterateCommittee(ctx, func(prop types.Committee) bool {
results = append(results, prop)
return false
})
return results
}
// // DeleteProposalAndVotes removes a proposal and its associated votes.
// func (k Keeper) DeleteProposalAndVotes(ctx sdk.Context, proposalID uint64) {
// votes := k.GetVotesByProposal(ctx, proposalID)
// k.DeleteProposal(ctx, proposalID)
// for _, v := range votes {
// k.DeleteVote(ctx, v.ProposalID, v.Voter)
// }
// }
// ------------------------------------------
// Votes
// ------------------------------------------
// GetVote gets a vote from the store.
func (k Keeper) GetVote(ctx sdk.Context, epochID uint64, voter sdk.ValAddress) (types.Vote, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix)
bz := store.Get(types.GetVoteKey(epochID, voter))
if bz == nil {
return types.Vote{}, false
}
var vote types.Vote
k.cdc.MustUnmarshal(bz, &vote)
return vote, true
}
// SetVote puts a vote into the store.
func (k Keeper) SetVote(ctx sdk.Context, vote types.Vote) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix)
bz := k.cdc.MustMarshal(&vote)
store.Set(types.GetVoteKey(vote.CommitteeID, vote.Voter), bz)
}
// DeleteVote removes a Vote from the store.
func (k Keeper) DeleteVote(ctx sdk.Context, committeeID uint64, voter sdk.ValAddress) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix)
store.Delete(types.GetVoteKey(committeeID, voter))
}
// IterateVotes provides an iterator over all stored votes.
// For each vote, cb will be called. If cb returns true, the iterator will close and stop.
func (k Keeper) IterateVotes(ctx sdk.Context, cb func(vote types.Vote) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.VoteKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var vote types.Vote
k.cdc.MustUnmarshal(iterator.Value(), &vote)
if cb(vote) {
break
}
}
}
// GetVotes returns all stored votes.
func (k Keeper) GetVotes(ctx sdk.Context) []types.Vote {
results := []types.Vote{}
k.IterateVotes(ctx, func(vote types.Vote) bool {
results = append(results, vote)
return false
})
return results
}
// GetVotesByProposal returns all votes for one proposal.
func (k Keeper) GetVotesByCommittee(ctx sdk.Context, committeeID uint64) []types.Vote {
results := []types.Vote{}
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), append(types.VoteKeyPrefix, types.GetKeyFromID(committeeID)...))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var vote types.Vote
k.cdc.MustUnmarshal(iterator.Value(), &vote)
results = append(results, vote)
}
return results
}
// ------------------------------------------
// Voters
// ------------------------------------------
func (k Keeper) SetVoter(ctx sdk.Context, voter sdk.ValAddress, pk vrf.PublicKey) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoterKeyPrefix)
store.Set(types.GetVoterKey(voter), pk)
fmt.Printf("voterStoreKey: %v, publicKey: %v\n", types.GetVoterKey(voter), pk)
}
func (k Keeper) IterateVoters(ctx sdk.Context, cb func(voter sdk.ValAddress, pk vrf.PublicKey) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.VoterKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
if cb(sdk.ValAddress(iterator.Key()[1:]), vrf.PublicKey(iterator.Value())) {
break
}
}
}
// GetVotes returns all stored voters
func (k Keeper) GetVoters(ctx sdk.Context) []sdk.ValAddress {
results := []sdk.ValAddress{}
k.IterateVoters(ctx, func(voter sdk.ValAddress, _ vrf.PublicKey) bool {
results = append(results, voter)
return false
})
return results
}
func (k Keeper) AddVoter(ctx sdk.Context, voter sdk.ValAddress, key []byte) error {
if len(key) != vrf.PublicKeySize {
return types.ErrInvalidPublicKey
}
k.SetVoter(ctx, voter, vrf.PublicKey(key))
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeRegister,
sdk.NewAttribute(types.AttributeKeyVoter, voter.String()),
// TODO: types.AttributeKeyPublicKey
),
)
return nil
}
func (k Keeper) AddVote(ctx sdk.Context, committeeID uint64, voter sdk.ValAddress, ballots []*types.Ballot) error {
// Validate
com, found := k.GetCommittee(ctx, committeeID)
if !found {
return errorsmod.Wrapf(types.ErrUnknownCommittee, "%d", committeeID)
}
if com.HasVotingEndedBy(ctx.BlockHeight()) {
return errorsmod.Wrapf(types.ErrProposalExpired, "%d ≥ %d", ctx.BlockHeight(), com.StartHeight)
}
// TODO: verify if the voter is registered
// TODO: verify whether ballots are valid or not
// Store vote, overwriting any prior vote
k.SetVote(ctx, types.NewVote(committeeID, voter, ballots))
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeVote,
sdk.NewAttribute(types.AttributeKeyCommitteeID, fmt.Sprintf("%d", com.ID)),
sdk.NewAttribute(types.AttributeKeyVoter, voter.String()),
// TODO: types.AttributeKeyBallots
),
)
return nil
}

View File

@ -0,0 +1,51 @@
// Copyright Tharsis Labs Ltd.(Evmos)
// SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE)
package keeper
import (
"context"
"github.com/0glabs/0g-chain/x/committee/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
var _ types.MsgServer = &Keeper{}
// Register handles MsgRegister messages
func (k Keeper) Register(goCtx context.Context, msg *types.MsgRegister) (*types.MsgRegisterResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
valAddr, err := sdk.ValAddressFromBech32(msg.Voter)
if err != nil {
return nil, err
}
_, found := k.stakingKeeper.GetValidator(ctx, valAddr)
if !found {
return nil, stakingtypes.ErrNoValidatorFound
}
if err := k.AddVoter(ctx, valAddr, msg.Key); err != nil {
return nil, err
}
return &types.MsgRegisterResponse{}, nil
}
// Vote handles MsgVote messages
func (k Keeper) Vote(goCtx context.Context, msg *types.MsgVote) (*types.MsgVoteResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
voter, err := sdk.ValAddressFromBech32(msg.Voter)
if err != nil {
return nil, err
}
if err := k.AddVote(ctx, msg.CommitteeID, voter, msg.Ballots); err != nil {
return nil, err
}
return &types.MsgVoteResponse{}, nil
}

View File

@ -0,0 +1,29 @@
package keeper
import (
"github.com/0glabs/0g-chain/x/committee/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.ParamsKey)
if len(bz) == 0 {
return params
}
k.cdc.MustUnmarshal(bz, &params)
return params
}
func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error {
store := ctx.KVStore(k.storeKey)
bz, err := k.cdc.Marshal(&params)
if err != nil {
return err
}
store.Set(types.ParamsKey, bz)
return nil
}

171
x/committee/v1/module.go Normal file
View File

@ -0,0 +1,171 @@
package committee
import (
"context"
"encoding/json"
"fmt"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
"github.com/0glabs/0g-chain/x/committee/v1/client/cli"
"github.com/0glabs/0g-chain/x/committee/v1/keeper"
"github.com/0glabs/0g-chain/x/committee/v1/types"
)
// consensusVersion defines the current x/committee module consensus version.
const consensusVersion = 1
// type check to ensure the interface is properly implemented
var (
_ module.AppModule = AppModule{}
_ module.AppModuleBasic = AppModuleBasic{}
_ module.AppModuleSimulation = AppModule{}
_ module.BeginBlockAppModule = AppModule{}
_ module.EndBlockAppModule = AppModule{}
)
// app module Basics object
type AppModuleBasic struct{}
// Name returns the inflation module's name.
func (AppModuleBasic) Name() string {
return types.ModuleName
}
// RegisterLegacyAminoCodec registers the inflation module's types on the given LegacyAmino codec.
func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {}
// ConsensusVersion returns the consensus state-breaking version for the module.
func (AppModuleBasic) ConsensusVersion() uint64 {
return consensusVersion
}
// RegisterInterfaces registers interfaces and implementations of the incentives
// module.
func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) {
types.RegisterInterfaces(interfaceRegistry)
}
// DefaultGenesis returns default genesis state as raw bytes for the incentives
// module.
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage {
return cdc.MustMarshalJSON(types.DefaultGenesisState())
}
// ValidateGenesis performs genesis state validation for the inflation module.
func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error {
var genesisState types.GenesisState
if err := cdc.UnmarshalJSON(bz, &genesisState); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)
}
return genesisState.Validate()
}
// RegisterRESTRoutes performs a no-op as the inflation module doesn't expose REST
// endpoints
func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {}
// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the inflation module.
func (b AppModuleBasic) RegisterGRPCGatewayRoutes(c client.Context, serveMux *runtime.ServeMux) {
if err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(c)); err != nil {
panic(err)
}
}
// GetTxCmd returns the root tx command for the inflation module.
func (AppModuleBasic) GetTxCmd() *cobra.Command { return cli.GetTxCmd() }
// GetQueryCmd returns no root query command for the inflation module.
func (AppModuleBasic) GetQueryCmd() *cobra.Command {
return cli.GetQueryCmd()
}
// ___________________________________________________________________________
// AppModule implements an application module for the inflation module.
type AppModule struct {
AppModuleBasic
keeper keeper.Keeper
sk *stakingkeeper.Keeper
}
// NewAppModule creates a new AppModule Object
func NewAppModule(
k keeper.Keeper,
sk *stakingkeeper.Keeper,
) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{},
keeper: k,
sk: sk,
}
}
// Name returns the inflation module's name.
func (AppModule) Name() string {
return types.ModuleName
}
// RegisterInvariants registers the inflation module invariants.
func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}
// RegisterServices registers a gRPC query service to respond to the
// module-specific gRPC queries.
func (am AppModule) RegisterServices(cfg module.Configurator) {
types.RegisterMsgServer(cfg.MsgServer(), am.keeper)
types.RegisterQueryServer(cfg.QueryServer(), am.keeper)
}
func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {
am.keeper.BeginBlock(ctx, req)
}
func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate {
am.keeper.EndBlock(ctx, req)
return []abci.ValidatorUpdate{}
}
// InitGenesis performs genesis initialization for the inflation module. It returns
// no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
cdc.MustUnmarshalJSON(data, &genesisState)
InitGenesis(ctx, am.keeper, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the inflation
// module.
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage {
gs := ExportGenesis(ctx, am.keeper)
return cdc.MustMarshalJSON(gs)
}
// ___________________________________________________________________________
// AppModuleSimulation functions
// GenerateGenesisState creates a randomized GenState of the inflation module.
func (am AppModule) GenerateGenesisState(_ *module.SimulationState) {
}
// RegisterStoreDecoder registers a decoder for inflation module's types.
func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {
}
// WeightedOperations doesn't return any inflation module operation.
func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation {
return []simtypes.WeightedOperation{}
}

View File

@ -0,0 +1,52 @@
package types
import (
"github.com/0glabs/0g-chain/crypto/vrf"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/msgservice"
)
var (
amino = codec.NewLegacyAmino()
// ModuleCdc references the global evm module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding.
ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
// AminoCdc is a amino codec created to support amino JSON compatible msgs.
AminoCdc = codec.NewAminoCodec(amino)
)
const (
// Amino names
registerName = "evmos/committee/MsgRegister"
voteName = "evmos/committee/MsgVote"
)
// NOTE: This is required for the GetSignBytes function
func init() {
RegisterLegacyAminoCodec(amino)
amino.Seal()
}
// RegisterInterfaces register implementations
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterImplementations(
(*sdk.Msg)(nil),
&MsgRegister{},
&MsgVote{},
)
registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &vrf.PubKey{})
registry.RegisterImplementations((*cryptotypes.PrivKey)(nil), &vrf.PrivKey{})
msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}
// RegisterLegacyAminoCodec required for EIP-712
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(&MsgRegister{}, registerName, nil)
cdc.RegisterConcrete(&MsgVote{}, voteName, nil)
}

View File

@ -0,0 +1,21 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type Committees []Committee
type Votes []Vote
func (c Committee) HasVotingEndedBy(height int64) bool {
return height >= int64(c.StartHeight)
}
// NewVote instantiates a new instance of Vote
func NewVote(committeeID uint64, voter sdk.ValAddress, ballots []*Ballot) Vote {
return Vote{
CommitteeID: committeeID,
Voter: voter,
Ballots: ballots,
}
}

View File

@ -0,0 +1,3 @@
package types
type Epoch struct{}

View File

@ -0,0 +1,19 @@
package types
import errorsmod "cosmossdk.io/errors"
var (
ErrUnknownCommittee = errorsmod.Register(ModuleName, 2, "committee not found")
ErrInvalidCommittee = errorsmod.Register(ModuleName, 3, "invalid committee")
ErrUnknownProposal = errorsmod.Register(ModuleName, 4, "proposal not found")
ErrProposalExpired = errorsmod.Register(ModuleName, 5, "proposal expired")
ErrInvalidPubProposal = errorsmod.Register(ModuleName, 6, "invalid pubproposal")
ErrUnknownVote = errorsmod.Register(ModuleName, 7, "vote not found")
ErrInvalidGenesis = errorsmod.Register(ModuleName, 8, "invalid genesis")
ErrNoProposalHandlerExists = errorsmod.Register(ModuleName, 9, "pubproposal has no corresponding handler")
ErrUnknownSubspace = errorsmod.Register(ModuleName, 10, "subspace not found")
ErrInvalidVoteType = errorsmod.Register(ModuleName, 11, "invalid vote type")
ErrNotFoundProposalTally = errorsmod.Register(ModuleName, 12, "proposal tally not found")
ErrInvalidPublicKey = errorsmod.Register(ModuleName, 13, "invalid public key")
ErrInvalidValidatorAddress = errorsmod.Register(ModuleName, 14, "invalid validator address")
)

View File

@ -0,0 +1,19 @@
package types
// Module event types
const (
EventTypeRegister = "register"
EventTypeVote = "vote"
AttributeValueCategory = "committee"
AttributeKeyCommitteeID = "committee_id"
AttributeKeyProposalID = "proposal_id"
AttributeKeyVotingStartHeight = "voting_start_height"
AttributeKeyVotingEndHeight = "voting_end_height"
AttributeKeyProposalCloseStatus = "status"
AttributeKeyVoter = "voter"
AttributeKeyBallots = "ballots"
AttributeKeyPublicKey = "public_key"
AttributeKeyProposalOutcome = "proposal_outcome"
AttributeKeyProposalTally = "proposal_tally"
)

View File

@ -0,0 +1,42 @@
package types
const (
DefaultVotingStartHeight = 1
DefaultVotingPeriod = 200
)
// NewGenesisState returns a new genesis state object for the module.
func NewGenesisState(params Params, votingStartHeight uint64, votingPeriod uint64, currentCommitteeID uint64, committees Committees) *GenesisState {
return &GenesisState{
Params: params,
VotingStartHeight: votingStartHeight,
VotingPeriod: votingPeriod,
CurrentCommitteeID: currentCommitteeID,
Committees: committees,
}
}
// DefaultGenesisState returns the default genesis state for the module.
func DefaultGenesisState() *GenesisState {
return NewGenesisState(
Params{
CommitteeSize: 1,
},
DefaultVotingStartHeight,
DefaultVotingPeriod,
1,
[]Committee{
{
ID: 1,
VotingStartHeight: DefaultVotingStartHeight,
StartHeight: DefaultVotingStartHeight + DefaultVotingPeriod,
EndHeight: DefaultVotingStartHeight + DefaultVotingPeriod*2,
Votes: Votes{},
}},
)
}
// Validate performs basic validation of genesis data.
func (gs GenesisState) Validate() error {
return nil
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,23 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// AccountKeeper defines the expected account keeper
type AccountKeeper interface {
GetAccount(sdk.Context, sdk.AccAddress) authtypes.AccountI
}
// BankKeeper defines the expected bank keeper interface
type BankKeeper interface {
GetSupply(ctx sdk.Context, denom string) sdk.Coin
GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin
}
type StakingKeeper interface {
BondDenom(ctx sdk.Context) (res string)
GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool)
}

View File

@ -0,0 +1,52 @@
package types
import (
"encoding/binary"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// ModuleName The name that will be used throughout the module
ModuleName = "committee"
// StoreKey Top level store key where all module items will be stored
StoreKey = ModuleName
)
// Key prefixes
var (
CommitteeKeyPrefix = []byte{0x00} // prefix for keys that store committees
VoteKeyPrefix = []byte{0x01} // prefix for keys that store votes
VoterKeyPrefix = []byte{0x02} // prefix for keys that store voters
ParamsKey = []byte{0x03}
VotingStartHeightKey = []byte{0x04}
VotingPeriodKey = []byte{0x05}
CurrentCommitteeIDKey = []byte{0x06}
)
// GetKeyFromID returns the bytes to use as a key for a uint64 id
func GetKeyFromID(id uint64) []byte {
return Uint64ToBytes(id)
}
func GetVoteKey(committeeID uint64, voter sdk.ValAddress) []byte {
return append(GetKeyFromID(committeeID), voter.Bytes()...)
}
func GetVoterKey(voter sdk.ValAddress) []byte {
return voter.Bytes()
}
// Uint64ToBytes converts a uint64 into fixed length bytes for use in store keys.
func Uint64ToBytes(id uint64) []byte {
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, uint64(id))
return bz
}
// Uint64FromBytes converts some fixed length bytes back into a uint64.
func Uint64FromBytes(bz []byte) uint64 {
return binary.BigEndian.Uint64(bz)
}

View File

@ -0,0 +1,65 @@
package types
import (
"encoding/hex"
"github.com/coniks-sys/coniks-go/crypto/vrf"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var _, _ sdk.Msg = &MsgRegister{}, &MsgVote{}
// GetSigners returns the expected signers for a MsgRegister message.
func (msg *MsgRegister) GetSigners() []sdk.AccAddress {
valAddr, err := sdk.ValAddressFromBech32(msg.Voter)
if err != nil {
panic(err)
}
accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(valAddr.Bytes()))
if err != nil {
panic(err)
}
return []sdk.AccAddress{accAddr}
}
// ValidateBasic does a sanity check of the provided data
func (msg *MsgRegister) ValidateBasic() error {
if _, err := sdk.ValAddressFromBech32(msg.Voter); err != nil {
return ErrInvalidValidatorAddress
}
if len(msg.Key) != vrf.PublicKeySize {
return ErrInvalidPublicKey
}
return nil
}
// GetSignBytes implements the LegacyMsg interface.
func (msg MsgRegister) GetSignBytes() []byte {
return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg))
}
// GetSigners returns the expected signers for a MsgVote message.
func (msg *MsgVote) GetSigners() []sdk.AccAddress {
valAddr, err := sdk.ValAddressFromBech32(msg.Voter)
if err != nil {
panic(err)
}
accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(valAddr.Bytes()))
if err != nil {
panic(err)
}
return []sdk.AccAddress{accAddr}
}
// ValidateBasic does a sanity check of the provided data
func (msg *MsgVote) ValidateBasic() error {
if _, err := sdk.ValAddressFromBech32(msg.Voter); err != nil {
return ErrInvalidValidatorAddress
}
return nil
}
// GetSignBytes implements the LegacyMsg interface.
func (msg MsgVote) GetSignBytes() []byte {
return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg))
}

Some files were not shown because too many files have changed in this diff Show More