sonr/scripts/test_node.sh
Prad Nukala 8010e6b069
Feature/update dockerfile (#6)
* chore: remove unused new.Dockerfile

* feat: add DID model definitions

* fix: Fix EncodePublicKey method in KeyInfo struct

* feat: Update `EncodePublicKey` to be the inverse of `DecodePublicKey`

* refactor: update AssetInfo protobuf definition

* fix: update default assets with correct asset types

* fix: Initialize IPFS client and check for mounted directories

* feat: Improve IPFS client initialization and mount checking

* feat: Add local filesystem check for IPFS and IPNS

* fix: Use Unixfs().Get() instead of Cat() for IPFS and IPNS content retrieval

* feat: Update GetCID and GetIPNS functions to read data from IPFS node

* fix: Ensure IPFS client is initialized before pinning CID

* feat: Add AddFile and AddFolder methods

* feat: add IPFS file system abstraction

* feat: Implement IPFS file, location, and filesystem abstractions

* refactor: remove unused functions and types

* refactor: remove unused FileSystem interface

* feat: add initial wasm entrypoint

* feat: add basic vault command operations

* docs: add vault module features

* test: remove test for MsgUpdateParams

* refactor: Replace PrimaryKey with Property struct in zkprop.go

* feat: Update the `CreateWitness` and `CreateAccumulator` and `VerifyWitness` and `UpdateAccumulator` to Use the new `Accumulator` and `Witness` types. Then Clean up the code in the file and refactor the marshalling methods

* <no value>

* feat: add KeyCurve and KeyType to KeyInfo in genesis

* feat: add WASM build step to devbox.json

* feat: Add zkgate.go file

* feat: Uncomment and modify zkgate code to work with Property struct

* feat: Merge zkgate.go and zkprop.go logic

* feat: implement API endpoints for profile management

* refactor: remove unused template file

* feat(orm): remove unused ORM models

* feat: add persistent SQLite database support in WASM

* fix: Update module names in protobuf files

* feat: Add method to initialize SQLite database

* fix: update go-sqlite3 dependency to version 1.14.23

* feat: introduce database layer

* feat: Implement database layer for Vault node

* feature/update-dockerfile

* feat: Add keyshares table

* fix: Reorder the SQL statements in the tables.go file

* feat: Update the `createCredentialsTable` method to match the proper Credential struct

* feat: Update createProfilesTable and add createPropertiesTable

* feat: Add constant SQL queries to queries.go and use prepared statements in db.go

* feat: Add createKeysharesTable to internal/db/db.go

* feat: Update `createPermissionsTable` to match Permissions struct

* feat: Add database enum types

* feat: Add DIDNamespace and PermissionScope enums

* feat: Add DBConfig and DBOption types

* feat: Update the db implementation to use the provided go library

* fix: update db implementation to use go-sqlite3 v0.18.2

* fix: Refactor database connection and statement handling

* feat: Simplify db.go implementation

* feat: Convert constant SQL queries to functions in queries.go and update db.go to use prepared statements

* feat: Add models.go file with database table structs

* fix: Remove unused statement map and prepare statements

diff --git a/internal/db/db.go b/internal/db/db.go
index 201d09b..d4d4d4e 100644
--- a/internal/db/db.go
+++ b/internal/db/db.go
@@ -32,11 +32,6 @@ func Open(config *DBConfig) (*DB, error) {
 		Conn: conn,
 	}

-	if err := createTables(db); err != nil {
-		conn.Close()
-		return nil, fmt.Errorf("failed to create tables: %w", err)
-	}
-
 	return db, nil
 }

@@ -61,114 +56,3 @@ func createTables(db *DB) error {
 	return nil
 }

-// AddAccount adds a new account to the database
-func (db *DB) AddAccount(name, address string) error {
-	return db.Exec(insertAccountQuery(name, address))
-}
-
-// AddAsset adds a new asset to the database
-func (db *DB) AddAsset(name, symbol string, decimals int, chainID int64) error {
-	return db.Exec(insertAssetQuery(name, symbol, decimals, chainID))
-}
-
-// AddChain adds a new chain to the database
-func (db *DB) AddChain(name, networkID string) error {
-	return db.Exec(insertChainQuery(name, networkID))
-}
-
-// AddCredential adds a new credential to the database
-func (db *DB) AddCredential(
-	handle, controller, attestationType, origin string,
-	credentialID, publicKey []byte,
-	transport string,
-	signCount uint32,
-	userPresent, userVerified, backupEligible, backupState, cloneWarning bool,
-) error {
-	return db.Exec(insertCredentialQuery(
-		handle,
-		controller,
-		attestationType,
-		origin,
-		credentialID,
-		publicKey,
-		transport,
-		signCount,
-		userPresent,
-		userVerified,
-		backupEligible,
-		backupState,
-		cloneWarning,
-	))
-}
-
-// AddProfile adds a new profile to the database
-func (db *DB) AddProfile(
-	id, subject, controller, originURI, publicMetadata, privateMetadata string,
-) error {
-	return db.statements["insertProfile"].Exec(
-		id, subject, controller, originURI, publicMetadata, privateMetadata,
-	)
-}
-
-// AddProperty adds a new property to the database
-func (db *DB) AddProperty(
-	profileID, key, accumulator, propertyKey string,
-) error {
-	return db.statements["insertProperty"].Exec(
-		profileID, key, accumulator, propertyKey,
-	)
-}
-
-// AddPermission adds a new permission to the database
-func (db *DB) AddPermission(
-	serviceID string,
-	grants []DIDNamespace,
-	scopes []PermissionScope,
-) error {
-	grantsJSON, err := json.Marshal(grants)
-	if err != nil {
-		return fmt.Errorf("failed to marshal grants: %w", err)
-	}
-
-	scopesJSON, err := json.Marshal(scopes)
-	if err != nil {
-		return fmt.Errorf("failed to marshal scopes: %w", err)
-	}
-
-	return db.statements["insertPermission"].Exec(
-		serviceID, string(grantsJSON), string(scopesJSON),
-	)
-}
-
-// GetPermission retrieves the permission for the given service ID
-func (db *DB) GetPermission(serviceID string) ([]DIDNamespace, []PermissionScope, error) {
-	row := db.statements["getPermission"].QueryRow(serviceID)
-
-	var grantsJSON, scopesJSON string
-	if err := row.Scan(&grantsJSON, &scopesJSON); err != nil {
-		return nil, nil, fmt.Errorf("failed to get permission: %w", err)
-	}
-
-	var grants []DIDNamespace
-	if err := json.Unmarshal([]byte(grantsJSON), &grants); err != nil {
-		return nil, nil, fmt.Errorf("failed to unmarshal grants: %w", err)
-	}
-
-	var scopes []PermissionScope
-	if err := json.Unmarshal([]byte(scopesJSON), &scopes); err != nil {
-		return nil, nil, fmt.Errorf("failed to unmarshal scopes: %w", err)
-	}
-
-	return grants, scopes, nil
-}
-
-// Close closes the database connection and finalizes all prepared statements
-func (db *DB) Close() error {
-	for _, stmt := range db.statements {
-		stmt.Finalize()
-	}
-	return db.Conn.Close()
-}
diff --git a/internal/db/queries.go b/internal/db/queries.go
index 807d701..e69de29 100644
--- a/internal/db/queries.go
+++ b/internal/db/queries.go
@@ -1,79 +0,0 @@
-package db
-
-import "fmt"
-
-// Account queries
-func insertAccountQuery(name, address string) string {
-	return fmt.Sprintf(`INSERT INTO accounts (name, address) VALUES (%s, %s)`, name, address)
-}
-
-// Asset queries
-func insertAssetQuery(name, symbol string, decimals int, chainID int64) string {
-	return fmt.Sprintf(
-		`INSERT INTO assets (name, symbol, decimals, chain_id) VALUES (%s, %s, %d, %d)`,
-		name,
-		symbol,
-		decimals,
-		chainID,
-	)
-}
-
-// Chain queries
-func insertChainQuery(name string, networkID string) string {
-	return fmt.Sprintf(`INSERT INTO chains (name, network_id) VALUES (%s, %d)`, name, networkID)
-}
-
-// Credential queries
-func insertCredentialQuery(
-	handle, controller, attestationType, origin string,
-	credentialID, publicKey []byte,
-	transport string,
-	signCount uint32,
-	userPresent, userVerified, backupEligible, backupState, cloneWarning bool,
-) string {
-	return fmt.Sprintf(`INSERT INTO credentials (
-		handle, controller, attestation_type, origin,
-		credential_id, public_key, transport, sign_count,
-		user_present, user_verified, backup_eligible,
-		backup_state, clone_warning
-	) VALUES (%s, %s, %s, %s, %s, %s, %s, %d, %t, %t, %t, %t, %t)`,
-		handle, controller, attestationType, origin,
-		credentialID, publicKey, transport, signCount,
-		userPresent, userVerified, backupEligible,
-		backupState, cloneWarning)
-}
-
-// Profile queries
-func insertProfileQuery(
-	id, subject, controller, originURI, publicMetadata, privateMetadata string,
-) string {
-	return fmt.Sprintf(`INSERT INTO profiles (
-		id, subject, controller, origin_uri,
-		public_metadata, private_metadata
-	) VALUES (%s, %s, %s, %s, %s, %s)`,
-		id, subject, controller, originURI,
-		publicMetadata, privateMetadata)
-}
-
-// Property queries
-func insertPropertyQuery(profileID, key, accumulator, propertyKey string) string {
-	return fmt.Sprintf(`INSERT INTO properties (
-		profile_id, key, accumulator, property_key
-	) VALUES (%s, %s, %s, %s)`,
-		profileID, key, accumulator, propertyKey)
-}
-
-// Permission queries
-func insertPermissionQuery(serviceID, grants, scopes string) string {
-	return fmt.Sprintf(
-		`INSERT INTO permissions (service_id, grants, scopes) VALUES (%s, %s, %s)`,
-		serviceID,
-		grants,
-		scopes,
-	)
-}
-
-// GetPermission query
-func getPermissionQuery(serviceID string) string {
-	return fmt.Sprintf(`SELECT grants, scopes FROM permissions WHERE service_id = %s`, serviceID)
-}

* fix: update Makefile to use sonrd instead of wasmd

* feat: Add targets for templ and vault in Makefile and use only make in devbox.json

* feat: add SQLite database support

* bump: version 0.6.0 → 0.7.0

* refactor: upgrade actions to latest versions
2024-09-05 01:24:57 -04:00

157 lines
5.8 KiB
Bash

#!/bin/bash
# Run this script to quickly install, setup, and run the current version of the network without docker.
#
# Examples:
# CHAIN_ID="local-1" HOME_DIR="~/.core" BLOCK_TIME="1000ms" CLEAN=true sh scripts/test_node.sh
# CHAIN_ID="local-2" HOME_DIR="~/.core" CLEAN=true RPC=36657 REST=2317 PROFF=6061 P2P=36656 GRPC=8090 GRPC_WEB=8091 ROSETTA=8081 BLOCK_TIME="500ms" sh scripts/test_node.sh
export KEY="user1"
export KEY2="user2"
export CHAIN_ID=${CHAIN_ID:-"sonr-testnet-1"}
export MONIKER="florence"
export KEYALGO="secp256k1"
export KEYRING=${KEYRING:-"test"}
export HOME_DIR=$(eval echo "${HOME_DIR:-"~/.sonr"}")
export BINARY=${BINARY:-sonrd}
export DENOM=${DENOM:-usnr}
export CLEAN=${CLEAN:-"true"}
export RPC=${RPC:-"26657"}
export REST=${REST:-"1317"}
export PROFF=${PROFF:-"6060"}
export P2P=${P2P:-"26656"}
export GRPC=${GRPC:-"9090"}
export GRPC_WEB=${GRPC_WEB:-"9091"}
export ROSETTA=${ROSETTA:-"8080"}
export BLOCK_TIME=${BLOCK_TIME:-"5s"}
# if which binary does not exist, exit
if [ -z `which $BINARY` ]; then
echo "Ensure $BINARY is installed and in your PATH"
exit 1
fi
alias BINARY="$BINARY --home=$HOME_DIR"
command -v $BINARY > /dev/null 2>&1 || { echo >&2 "$BINARY command not found. Ensure this is setup / properly installed in your GOPATH (make install)."; exit 1; }
command -v jq > /dev/null 2>&1 || { echo >&2 "jq not installed. More info: https://stedolan.github.io/jq/download/"; exit 1; }
set_config() {
$BINARY config set client chain-id $CHAIN_ID
$BINARY config set client keyring-backend $KEYRING
}
set_config
from_scratch () {
# Fresh install on current branch
make install
# remove existing daemon files.
if [ ${#HOME_DIR} -le 2 ]; then
echo "HOME_DIR must be more than 2 characters long"
return
fi
rm -rf $HOME_DIR && echo "Removed $HOME_DIR"
# reset values if not set already after whipe
set_config
add_key() {
key=$1
mnemonic=$2
echo $mnemonic | BINARY keys add $key --keyring-backend $KEYRING --algo $KEYALGO --recover
}
# idx1efd63aw40lxf3n4mhf7dzhjkr453axur9vjt6y
add_key $KEY "decorate bright ozone fork gallery riot bus exhaust worth way bone indoor calm squirrel merry zero scheme cotton until shop any excess stage laundry"
# idx1hj5fveer5cjtn4wd6wstzugjfdxzl0xpecp0nd
add_key $KEY2 "wealth flavor believe regret funny network recall kiss grape useless pepper cram hint member few certain unveil rather brick bargain curious require crowd raise"
# chain initial setup
BINARY init $MONIKER --chain-id $CHAIN_ID --default-denom $DENOM
update_test_genesis () {
cat $HOME_DIR/config/genesis.json | jq "$1" > $HOME_DIR/config/tmp_genesis.json && mv $HOME_DIR/config/tmp_genesis.json $HOME_DIR/config/genesis.json
}
# === CORE MODULES ===
# Block
update_test_genesis '.consensus_params["block"]["max_gas"]="100000000"'
# Gov
update_test_genesis `printf '.app_state["gov"]["params"]["min_deposit"]=[{"denom":"%s","amount":"1000000"}]' $DENOM`
update_test_genesis '.app_state["gov"]["params"]["voting_period"]="30s"'
update_test_genesis '.app_state["gov"]["params"]["expedited_voting_period"]="15s"'
# staking
update_test_genesis `printf '.app_state["staking"]["params"]["bond_denom"]="%s"' $DENOM`
update_test_genesis '.app_state["staking"]["params"]["min_commission_rate"]="0.050000000000000000"'
# mint
update_test_genesis `printf '.app_state["mint"]["params"]["mint_denom"]="%s"' $DENOM`
# crisis
update_test_genesis `printf '.app_state["crisis"]["constant_fee"]={"denom":"%s","amount":"1000"}' $DENOM`
# === CUSTOM MODULES ===
# globalfee
update_test_genesis `printf '.app_state["globalfee"]["params"]["minimum_gas_prices"]=[{"amount":"0.000000000000000000","denom":"%s"}]' $DENOM`
# tokenfactory
update_test_genesis '.app_state["tokenfactory"]["params"]["denom_creation_fee"]=[]'
update_test_genesis '.app_state["tokenfactory"]["params"]["denom_creation_gas_consume"]=100000'
# poa
update_test_genesis '.app_state["poa"]["params"]["admins"]=["idx10d07y265gmmuvt4z0w9aw880jnsr700j9kqcfa"]'
# Allocate genesis accounts
BINARY genesis add-genesis-account $KEY 10000000$DENOM,900snr --keyring-backend $KEYRING
BINARY genesis add-genesis-account $KEY2 10000000$DENOM,800snr --keyring-backend $KEYRING
# Sign genesis transaction
BINARY genesis gentx $KEY 1000000$DENOM --keyring-backend $KEYRING --chain-id $CHAIN_ID
BINARY genesis collect-gentxs
BINARY genesis validate-genesis
err=$?
if [ $err -ne 0 ]; then
echo "Failed to validate genesis"
return
fi
}
# check if CLEAN is not set to false
if [ "$CLEAN" != "false" ]; then
echo "Starting from a clean state"
from_scratch
fi
echo "Starting node..."
# Opens the RPC endpoint to outside connections
sed -i 's/laddr = "tcp:\/\/127.0.0.1:26657"/c\laddr = "tcp:\/\/0.0.0.0:'$RPC'"/g' $HOME_DIR/config/config.toml
sed -i 's/cors_allowed_origins = \[\]/cors_allowed_origins = \["\*"\]/g' $HOME_DIR/config/config.toml
# REST endpoint
sed -i 's/address = "tcp:\/\/localhost:1317"/address = "tcp:\/\/0.0.0.0:'$REST'"/g' $HOME_DIR/config/app.toml
sed -i 's/enable = false/enable = true/g' $HOME_DIR/config/app.toml
# peer exchange
sed -i 's/pprof_laddr = "localhost:6060"/pprof_laddr = "localhost:'$PROFF_LADDER'"/g' $HOME_DIR/config/config.toml
sed -i 's/laddr = "tcp:\/\/0.0.0.0:26656"/laddr = "tcp:\/\/0.0.0.0:'$P2P'"/g' $HOME_DIR/config/config.toml
# GRPC
sed -i 's/address = "localhost:9090"/address = "0.0.0.0:'$GRPC'"/g' $HOME_DIR/config/app.toml
sed -i 's/address = "localhost:9091"/address = "0.0.0.0:'$GRPC_WEB'"/g' $HOME_DIR/config/app.toml
# Rosetta Api
sed -i 's/address = ":8080"/address = "0.0.0.0:'$ROSETTA'"/g' $HOME_DIR/config/app.toml
# Faster blocks
sed -i 's/timeout_commit = "5s"/timeout_commit = "'$BLOCK_TIME'"/g' $HOME_DIR/config/config.toml
# Start the node with 0 gas fees
BINARY start --pruning=nothing --minimum-gas-prices=0$DENOM --rpc.laddr="tcp://0.0.0.0:$RPC"