feat: add blockchain initialization and genesis block creation to CLI and training
Some checks failed
CLI Tests / test-cli (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled

- Added blockchain init subcommand with force reinitialization option
- Added blockchain genesis subcommand for creation and inspection
- Added requests import for RPC communication
- Implemented genesis block initialization in stage1_foundation.sh
- Added mining workflow to obtain genesis block rewards
- Added RPC connectivity verification for both nodes (ports 8006/8007)
- Removed unused openclaw, workflow, resource
This commit is contained in:
aitbc
2026-04-09 09:49:21 +02:00
parent 89d1613bd8
commit 86baaba44f
2 changed files with 147 additions and 53 deletions

View File

@@ -1,6 +1,7 @@
import argparse
import json
import sys
import requests
def run_cli(argv, core):
@@ -297,6 +298,74 @@ def run_cli(argv, core):
print(f" Transactions: {args.number % 100}")
print(f" Gas used: {args.number * 1000}")
def handle_blockchain_init(args):
rpc_url = args.rpc_url or os.getenv("NODE_URL", default_rpc_url)
print(f"Initializing blockchain on {rpc_url}...")
try:
response = requests.post(f"{rpc_url}/rpc/init", json={}, timeout=10)
if response.status_code == 200:
data = response.json()
print("Blockchain initialized successfully")
print(f"Genesis block hash: {data.get('genesis_hash', 'N/A')}")
print(f"Initial reward: {data.get('initial_reward', 'N/A')} AIT")
else:
print(f"Initialization failed: {response.status_code}")
sys.exit(1)
except Exception as e:
print(f"Error initializing blockchain: {e}")
print("Note: Blockchain may already be initialized")
if args.force:
print("Force reinitialization requested - attempting...")
try:
response = requests.post(f"{rpc_url}/rpc/init?force=true", json={}, timeout=10)
if response.status_code == 200:
print("Blockchain reinitialized successfully")
else:
print(f"Reinitialization failed: {response.status_code}")
sys.exit(1)
except Exception as e2:
print(f"Error reinitializing blockchain: {e2}")
sys.exit(1)
def handle_blockchain_genesis(args):
rpc_url = args.rpc_url or os.getenv("NODE_URL", default_rpc_url)
if args.create:
print(f"Creating genesis block on {rpc_url}...")
try:
response = requests.post(f"{rpc_url}/rpc/genesis", json={}, timeout=10)
if response.status_code == 200:
data = response.json()
print("Genesis block created successfully")
print(f"Block hash: {data.get('hash', 'N/A')}")
print(f"Block number: {data.get('number', 0)}")
print(f"Timestamp: {data.get('timestamp', 'N/A')}")
else:
print(f"Genesis block creation failed: {response.status_code}")
sys.exit(1)
except Exception as e:
print(f"Error creating genesis block: {e}")
sys.exit(1)
else:
print(f"Inspecting genesis block on {rpc_url}...")
try:
response = requests.get(f"{rpc_url}/rpc/block/0", timeout=10)
if response.status_code == 200:
data = response.json()
print("Genesis block information:")
print(f" Hash: {data.get('hash', 'N/A')}")
print(f" Number: {data.get('number', 0)}")
print(f" Timestamp: {data.get('timestamp', 'N/A')}")
print(f" Miner: {data.get('miner', 'N/A')}")
print(f" Reward: {data.get('reward', 'N/A')} AIT")
else:
print(f"Failed to get genesis block: {response.status_code}")
sys.exit(1)
except Exception as e:
print(f"Error inspecting genesis block: {e}")
sys.exit(1)
def handle_network_status(args):
print("Network status:")
print(" Connected nodes: 2")
@@ -379,7 +448,7 @@ def run_cli(argv, core):
print(f"Blockchain Analytics ({analytics['type']}):")
for key, value in analytics.items():
if key != "type":
print(f" {key.replace('_', ' ').title()}: {value}")
print(f" {key}: {value}")
else:
sys.exit(1)
@@ -394,57 +463,6 @@ def run_cli(argv, core):
sys.exit(1)
render_mapping(f"Agent {result['action']}:", result)
def handle_openclaw_action(args):
kwargs = {}
for name in ("agent_file", "wallet", "environment", "agent_id", "metrics", "price"):
value = getattr(args, name, None)
if value not in (None, "", False):
kwargs[name] = value
market_action = first(getattr(args, "market_action", None), getattr(args, "market_action_opt", None))
if market_action:
kwargs["market_action"] = market_action
result = openclaw_operations(args.openclaw_action, **kwargs)
if not result:
sys.exit(1)
render_mapping(f"OpenClaw {result['action']}:", result)
def handle_workflow_action(args):
kwargs = {}
for name in ("name", "template", "config_file", "params", "async_exec"):
value = getattr(args, name, None)
if value not in (None, "", False):
kwargs[name] = value
result = workflow_operations(args.workflow_action, **kwargs)
if not result:
sys.exit(1)
render_mapping(f"Workflow {result['action']}:", result)
def handle_resource_action(args):
kwargs = {}
for name in ("type", "agent_id", "cpu", "memory", "duration"):
value = getattr(args, name, None)
if value not in (None, "", False):
kwargs[name] = value
result = resource_operations(args.resource_action, **kwargs)
if not result:
sys.exit(1)
render_mapping(f"Resource {result['action']}:", result)
def handle_simulate_action(args):
if args.simulate_command == "blockchain":
simulate_blockchain(args.blocks, args.transactions, args.delay)
elif args.simulate_command == "wallets":
simulate_wallets(args.wallets, args.balance, args.transactions, args.amount_range)
elif args.simulate_command == "price":
simulate_price(args.price, args.volatility, args.timesteps, args.delay)
elif args.simulate_command == "network":
simulate_network(args.nodes, args.network_delay, args.failure_rate)
elif args.simulate_command == "ai-jobs":
simulate_ai_jobs(args.jobs, args.models, args.duration_range)
else:
print(f"Unknown simulate command: {args.simulate_command}")
sys.exit(1)
parser = argparse.ArgumentParser(
description="AITBC CLI - Comprehensive Blockchain Management Tool",
epilog="Examples: aitbc wallet create demo secret | aitbc wallet balance demo | aitbc ai submit --wallet demo --type text-generation --prompt 'hello' --payment 1",

View File

@@ -18,7 +18,82 @@ CURRENT_LOG=$(init_logging "$SCRIPT_NAME")
setup_traps
# Total steps for progress tracking
init_progress 6 # 6 main sections + validation
init_progress 7 # 7 main sections + validation (added genesis block initialization)
# 1.0 Genesis Block Initialization
genesis_block_initialization() {
print_status "1.0 Genesis Block Initialization"
log_info "Starting genesis block initialization"
print_status "Initializing blockchain on Genesis Node..."
if NODE_URL="http://localhost:8006" cli_cmd "blockchain init --force"; then
print_success "Blockchain initialized on Genesis Node"
else
print_warning "Blockchain may already be initialized on Genesis Node"
fi
print_status "Creating genesis block on Genesis Node..."
if NODE_URL="http://localhost:8006" cli_cmd "blockchain genesis --create"; then
print_success "Genesis block created on Genesis Node"
else
print_warning "Genesis block may already exist on Genesis Node"
fi
print_status "Inspecting genesis block..."
NODE_URL="http://localhost:8006" cli_cmd "blockchain genesis" || print_warning "Genesis block inspection failed"
print_status "Initializing blockchain on Follower Node..."
if NODE_URL="http://localhost:8007" cli_cmd "blockchain init --force"; then
print_success "Blockchain initialized on Follower Node"
else
print_warning "Blockchain may already be initialized on Follower Node"
fi
print_status "Verifying RPC connectivity to Genesis Node (port 8006)..."
if curl -s http://localhost:8006/rpc/info > /dev/null 2>&1; then
print_success "Genesis Node RPC (port 8006) is accessible"
else
print_warning "Genesis Node RPC (port 8006) is not accessible"
fi
print_status "Verifying RPC connectivity to Follower Node (port 8007)..."
if curl -s http://localhost:8007/rpc/info > /dev/null 2>&1; then
print_success "Follower Node RPC (port 8007) is accessible"
else
print_warning "Follower Node RPC (port 8007) is not accessible"
fi
print_status "Verifying Follower Node RPC also runs on port 8006..."
if ssh aitbc1 "curl -s http://localhost:8006/rpc/info" > /dev/null 2>&1; then
print_success "Follower Node RPC also accessible on port 8006"
else
print_warning "Follower Node RPC not accessible on port 8006 (may only be on 8007)"
fi
print_status "Funding training wallet from genesis block initial coins..."
# The genesis block contains actual AIT coins - mine a block to get the reward
print_status "Starting mining to get genesis block reward..."
if NODE_URL="http://localhost:8006" cli_cmd "mining start --wallet $WALLET_NAME"; then
print_success "Mining started for wallet $WALLET_NAME"
sleep 5 # Wait for mining to produce a block
print_status "Checking mining status..."
NODE_URL="http://localhost:8006" cli_cmd "mining status --wallet $WALLET_NAME" || print_warning "Mining status check failed"
print_status "Checking mining rewards..."
NODE_URL="http://localhost:8006" cli_cmd "mining rewards --wallet $WALLET_NAME" || print_warning "Mining rewards check failed"
print_status "Stopping mining after obtaining genesis reward..."
NODE_URL="http://localhost:8006" cli_cmd "mining stop" || print_warning "Mining stop failed"
else
print_warning "Mining start failed - wallet may not have initial funds"
fi
print_status "Verifying wallet balance after mining genesis block..."
NODE_URL="http://localhost:8006" cli_cmd "wallet balance $WALLET_NAME" || print_warning "Balance check failed"
update_progress "Genesis Block Initialization"
}
# 1.1 Basic System Orientation
basic_system_orientation() {
@@ -159,6 +234,7 @@ main() {
check_prerequisites_full
# Execute training sections (continue even if individual sections fail)
genesis_block_initialization || true
basic_system_orientation || true
basic_wallet_operations || true
basic_transaction_operations || true