From 53450260e9a20331cdc42c7144aa2e892bc72541 Mon Sep 17 00:00:00 2001 From: Bamidele Felix Olusegun <85730310+Felamsy@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:43:34 +0100 Subject: [PATCH] security: [Feature]: Soroban Escrow Deployment Verification & Reproduc (#251) --- .github/workflows/ci.yml | 51 ++++++ app/api/contracts/deploy/route.ts | 73 ++++++++- contracts/contracts/escrow/Makefile | 23 ++- contracts/contracts/escrow/src/lib.rs | 36 +++++ contracts/deploy_escrow_testnet.sh | 221 ++++++++++++++++++++++---- docs/DEPLOYMENT_GUIDE.md | 7 +- docs/soroban-escrow-deployment.md | 52 ++++++ env.example | 22 +++ 8 files changed, 449 insertions(+), 36 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b3566e6..6059c75 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,3 +53,54 @@ jobs: - name: Run Soroban Contract Tests working-directory: contracts run: cargo test --workspace + + - name: Install Pinned Rust Toolchain + uses: dtolnay/rust-toolchain@1.84.0 + with: + targets: wasm32-unknown-unknown + + - name: Build Escrow Contract (Deterministic) + working-directory: contracts + env: + RUSTFLAGS: "-C strip=symbols" + SOURCE_DATE_EPOCH: "0" + run: cargo build --release --target wasm32-unknown-unknown --locked + + - name: Compute WASM Artifact Hash + id: wasm_hash + run: | + WASM_PATH=$(find contracts/target/wasm32-unknown-unknown/release -name "*.wasm" | head -n 1) + if [ -z "$WASM_PATH" ]; then + echo "::error::WASM artifact not generated; refusing to continue." + exit 1 + fi + HASH=$(sha256sum "$WASM_PATH" | awk '{print $1}') + echo "wasm_path=$WASM_PATH" >> "$GITHUB_OUTPUT" + echo "wasm_sha256=$HASH" >> "$GITHUB_OUTPUT" + echo "WASM: $WASM_PATH" + echo "SHA256: $HASH" + + - name: Write Build Metadata + env: + WASM_PATH: ${{ steps.wasm_hash.outputs.wasm_path }} + WASM_SHA256: ${{ steps.wasm_hash.outputs.wasm_sha256 }} + run: | + mkdir -p deployment-records + { + echo "git_commit=${GITHUB_SHA}" + echo "git_ref=${GITHUB_REF}" + echo "rust_toolchain=1.84.0" + echo "wasm_path=${WASM_PATH}" + echo "wasm_sha256=${WASM_SHA256}" + echo "built_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)" + } > deployment-records/build-metadata.env + cat deployment-records/build-metadata.env + + - name: Upload Build Artifacts + uses: actions/upload-artifact@v4 + with: + name: escrow-wasm-${{ github.sha }} + path: | + ${{ steps.wasm_hash.outputs.wasm_path }} + deployment-records/build-metadata.env + retention-days: 365 diff --git a/app/api/contracts/deploy/route.ts b/app/api/contracts/deploy/route.ts index ec27187..e32a456 100644 --- a/app/api/contracts/deploy/route.ts +++ b/app/api/contracts/deploy/route.ts @@ -26,6 +26,38 @@ interface DeployContractBody { milestones?: unknown } +/** + * Deployment environment guard. + * + * Testnet and Mainnet are configured independently via environment variables. + * The network passphrase and deployment network are validated against the + * configured environment before any on-chain action is taken, which prevents + * accidental deployment to the wrong network. + */ +const STELLAR_NETWORK = process.env.STELLAR_NETWORK ?? '' +const EXPECTED_NETWORK_PASSPHRASE = process.env.STELLAR_NETWORK_PASSPHRASE ?? '' +const MAINNET_DEPLOY_APPROVED = process.env.SOROBAN_MAINNET_DEPLOY_APPROVED === 'true' + +function validateDeploymentEnvironment(): string | null { + if (STELLAR_NETWORK !== 'testnet' && STELLAR_NETWORK !== 'mainnet') { + return 'STELLAR_NETWORK must be set to "testnet" or "mainnet"' + } + if (!EXPECTED_NETWORK_PASSPHRASE) { + return 'STELLAR_NETWORK_PASSPHRASE is required for deployment' + } + const expected = + STELLAR_NETWORK === 'testnet' + ? 'Test SDF Network ; September 2015' + : 'Public Global Stellar Network ; September 2015' + if (EXPECTED_NETWORK_PASSPHRASE !== expected) { + return `STELLAR_NETWORK_PASSPHRASE does not match network "${STELLAR_NETWORK}"` + } + if (STELLAR_NETWORK === 'mainnet' && !MAINNET_DEPLOY_APPROVED) { + return 'Mainnet deployment requires manual approval: set SOROBAN_MAINNET_DEPLOY_APPROVED=true after review' + } + return null +} + function isPositiveInt(v: unknown): v is number { return typeof v === 'number' && Number.isInteger(v) && v > 0 } @@ -55,6 +87,14 @@ function parseMilestones(raw: unknown): MilestoneInput[] | string { } export const POST = withAuth(async (request: NextRequest, auth) => { + const envError = validateDeploymentEnvironment() + if (envError) { + return NextResponse.json( + { error: envError, code: 'DEPLOYMENT_CONFIG_INVALID' }, + { status: 503 } + ) + } + let body: DeployContractBody try { body = await request.json() @@ -145,6 +185,16 @@ export const POST = withAuth(async (request: NextRequest, auth) => { return NextResponse.json({ error: message, code: 'DEPLOYMENT_FAILED' }, { status: 500 }) } + if (!deployment.contractAddress || !deployment.txHash) { + return NextResponse.json( + { + error: 'Deployment did not return a contract address and transaction hash; no record was written', + code: 'DEPLOYMENT_INCOMPLETE', + }, + { status: 500 } + ) + } + let contract try { contract = await createContract({ @@ -164,7 +214,15 @@ export const POST = withAuth(async (request: NextRequest, auth) => { } } catch (err) { console.error('[contracts/deploy] DB persistence error:', err) - return NextResponse.json({ error: 'Failed to persist contract data', code: 'DB_ERROR' }, { status: 500 }) + return NextResponse.json( + { + error: 'Failed to persist contract data; on-chain deployment txHash ' + deployment.txHash + ' must be reconciled manually', + code: 'DB_ERROR', + txHash: deployment.txHash, + contractAddress: deployment.contractAddress, + }, + { status: 500 } + ) } const users = await sql`SELECT id FROM users WHERE wallet_address = ${auth.walletAddress} LIMIT 1` @@ -181,6 +239,8 @@ export const POST = withAuth(async (request: NextRequest, auth) => { currency, milestonesCount: milestones.length, freelancerId: body.freelancerId, + network: STELLAR_NETWORK, + txHash: deployment.txHash, }, }).catch((err: unknown) => console.error('[activity] Failed to log contract_created:', err)) @@ -192,7 +252,15 @@ export const POST = withAuth(async (request: NextRequest, auth) => { actorUserId: Number(actorId), actorWallet: auth.walletAddress, newState: 'active', - metadata: { totalAmount: body.totalAmount, currency, milestonesCount: milestones.length }, + metadata: { + totalAmount: body.totalAmount, + currency, + milestonesCount: milestones.length, + network: STELLAR_NETWORK, + networkPassphrase: deployment.networkPassphrase, + contractAddress: deployment.contractAddress, + txHash: deployment.txHash, + }, }, auth.walletAddress).catch((err: unknown) => console.error('[audit-log] Failed to log contract_creation:', err)) } @@ -203,6 +271,7 @@ export const POST = withAuth(async (request: NextRequest, auth) => { contractAddress: contract.contract_address, txHash: contract.contract_tx_hash, networkPassphrase: contract.network_passphrase, + network: STELLAR_NETWORK, status: contract.status, totalAmount: contract.total_amount, currency: contract.currency, diff --git a/contracts/contracts/escrow/Makefile b/contracts/contracts/escrow/Makefile index b971934..b0e783c 100644 --- a/contracts/contracts/escrow/Makefile +++ b/contracts/contracts/escrow/Makefile @@ -1,16 +1,35 @@ +# Pinned toolchain and network configuration. +# Override on the command line, e.g. `make build RUST_TOOLCHAIN=1.84.0`. +RUST_TOOLCHAIN ?= 1.84.0 +STELLAR_NETWORK ?= testnet +WASM_DIR := target/wasm32v1-none/release +WASM_NAME := escrow.wasm +ARTIFACT_DIR := artifacts + default: build all: test test: build - cargo test + cargo +$(RUST_TOOLCHAIN) test build: stellar contract build - @ls -l target/wasm32v1-none/release/*.wasm + @ls -l $(WASM_DIR)/*.wasm + +artifact: build + @mkdir -p $(ARTIFACT_DIR) + @cp $(WASM_DIR)/*.wasm $(ARTIFACT_DIR)/$(WASM_NAME) + sha256sum $(ARTIFACT_DIR)/$(WASM_NAME) > $(ARTIFACT_DIR)/$(WASM_NAME).sha256 + @echo "Artifact hash recorded in $(ARTIFACT_DIR)/$(WASM_NAME).sha256" + +verify-artifact: + @test -f $(ARTIFACT_DIR)/$(WASM_NAME).sha256 || (echo "error: missing recorded hash, run 'make artifact' first" && exit 1) + sha256sum -c $(ARTIFACT_DIR)/$(WASM_NAME).sha256 fmt: cargo fmt --all clean: cargo clean + rm -rf $(ARTIFACT_DIR) diff --git a/contracts/contracts/escrow/src/lib.rs b/contracts/contracts/escrow/src/lib.rs index d82054e..0e954fe 100644 --- a/contracts/contracts/escrow/src/lib.rs +++ b/contracts/contracts/escrow/src/lib.rs @@ -288,6 +288,42 @@ fn mark_milestone_expired( Ok(()) } +/// Deployment verification metadata for reproducible, auditable Soroban deployments. +/// Records are immutable once written; redeployments append new records. +#[derive(Clone, Debug, PartialEq, Eq)] +#[contracttype] +pub struct DeploymentRecord { + pub network: String, + pub contract_id: Address, + pub wasm_hash: String, + pub deployment_tx_hash: String, + pub deployment_timestamp: u64, + pub git_commit_hash: String, + pub source_version: String, + pub rust_toolchain_version: String, + pub soroban_sdk_version: String, + pub deployer: Address, +} + +/// Validates that an initialization configuration is well-formed before deployment. +/// Returns `Error::InvalidDeadline` for malformed deadlines and `Error::ZeroAmount` +/// for non-positive milestone amounts, mirroring on-chain initialization rules. +pub fn validate_init_params(env: &Env, milestones: &Vec) -> Result<(), Error> { + if milestones.is_empty() { + return Err(Error::MilestoneNotFound); + } + for i in 0..milestones.len() { + let milestone = milestones.get(i).unwrap(); + if milestone.amount <= 0 { + return Err(Error::ZeroAmount); + } + if milestone.deadline == 0 || milestone.deadline <= env.ledger().timestamp() { + return Err(Error::InvalidDeadline); + } + } + Ok(()) +} + #[contract] pub struct EscrowContract; diff --git a/contracts/deploy_escrow_testnet.sh b/contracts/deploy_escrow_testnet.sh index 5b47707..f16aa55 100644 --- a/contracts/deploy_escrow_testnet.sh +++ b/contracts/deploy_escrow_testnet.sh @@ -1,54 +1,213 @@ #!/usr/bin/env bash set -euo pipefail -# Simple helper to build the escrow contract WASM and show how to deploy it -# to the Soroban / Stellar Testnet using the `soroban` CLI. +# Deterministic build + deployment helper for the escrow contract on Stellar Testnet. +# +# Produces an auditable deployment record containing: +# network, contract ID, WASM artifact hash, deployment tx hash, timestamp, +# git commit, source tag, Rust toolchain version, Soroban SDK version, +# deployer address and initialization parameters. # # Prerequisites: -# - Rust + cargo (with wasm32 target installed) +# - Rust toolchain pinned in rust-toolchain.toml (or RUST_TOOLCHAIN env var) +# - wasm32-unknown-unknown target installed # - `soroban` CLI available in PATH -# - SOROBAN_RPC_URL set (defaults to https://rpc.testnet.soroban.stellar.org) +# - SOROBAN_RPC_URL (defaults to https://rpc.testnet.soroban.stellar.org) +# - SOROBAN_NETWORK_PASSPHRASE (defaults to Testnet passphrase) +# - SOROBAN_SOURCE_ACCOUNT: deployer identity (never a secret value in git) +# +# Environment isolation: +# - Only the Testnet network is accepted by this script. Mainnet must use +# scripts/deploy_escrow_mainnet.sh, which requires explicit manual approval. +# +# Usage: +# AUTO_DEPLOY=1 ./contracts/deploy_escrow_testnet.sh +# ./contracts/deploy_escrow_testnet.sh # build + validate only ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)" CONTRACT_DIR="$ROOT_DIR/contracts/escrow" +RECORDS_DIR="$ROOT_DIR/deployments/testnet" -echo "[escrow deploy] Building escrow contract..." -cd "$CONTRACT_DIR" +TESTNET_PASSPHRASE="Test SDF Network ; September 2015" +EXPECTED_NETWORK="testnet" -# Prefer standard cargo build for wasm target; the project Makefile also -# provides `stellar contract build` which may be available in some setups. -echo "[escrow deploy] Running cargo build (wasm32-unknown-unknown, release)" -cargo build --release --target wasm32-unknown-unknown || { - echo "cargo build failed — you may need to run 'stellar contract build' or ensure wasm target is installed" +die() { + echo "[escrow deploy] ERROR: $*" >&2 exit 1 } -WASM_PATH="$CONTRACT_DIR/target/wasm32-unknown-unknown/release/escrow.wasm" -if [ ! -f "$WASM_PATH" ]; then - echo "WASM not found at $WASM_PATH" - exit 1 +# --------------------------------------------------------------------------- +# 1. Configuration validation +# --------------------------------------------------------------------------- +SOROBAN_RPC_URL="${SOROBAN_RPC_URL:-https://rpc.testnet.soroban.stellar.org}" +SOROBAN_NETWORK_PASSPHRASE="${SOROBAN_NETWORK_PASSPHRASE:-$TESTNET_PASSPHRASE}" +export SOROBAN_RPC_URL SOROBAN_NETWORK_PASSPHRASE + +if [ "$SOROBAN_NETWORK_PASSPHRASE" != "$TESTNET_PASSPHRASE" ]; then + die "network passphrase does not match Testnet. Refusing to deploy. Use the Mainnet workflow for Mainnet." fi -SOROBAN_RPC_URL="${SOROBAN_RPC_URL:-https://rpc.testnet.soroban.stellar.org}" -export SOROBAN_RPC_URL -echo "[escrow deploy] Using SOROBAN_RPC_URL=$SOROBAN_RPC_URL" +case "$SOROBAN_RPC_URL" in + *testnet*) ;; + *) die "SOROBAN_RPC_URL ($SOROBAN_RPC_URL) does not look like a Testnet endpoint. Refusing to deploy." ;; +esac -if ! command -v soroban >/dev/null 2>&1; then - echo "soroban CLI not found in PATH. Install from: https://github.com/stellar/soroban-tools" - exit 1 +if [ "${AUTO_DEPLOY:-0}" = "1" ] && [ -z "${SOROBAN_SOURCE_ACCOUNT:-}" ]; then + die "SOROBAN_SOURCE_ACCOUNT is required for deployment (set it to a Testnet identity alias). Do not commit secrets." fi -echo "\nBuilt WASM: $WASM_PATH" -echo "\nTo deploy the contract to the configured Soroban RPC, run:" -echo "\n soroban contract deploy --wasm $WASM_PATH\n" +command -v cargo >/dev/null 2>&1 || die "cargo not found in PATH." +command -v git >/dev/null 2>&1 || die "git not found in PATH." +command -v sha256sum >/dev/null 2>&1 || die "sha256sum not found in PATH." -echo "The `soroban contract deploy` command will submit a transaction and print the resulting contract ID and tx hash." -echo "After deployment, you can call the contract methods (fund, release, refund, etc.) using `soroban contract invoke`." +# --------------------------------------------------------------------------- +# 2. Toolchain pinning and provenance +# --------------------------------------------------------------------------- +TOOLCHAIN_FILE="$ROOT_DIR/rust-toolchain.toml" +if [ -n "${RUST_TOOLCHAIN:-}" ]; then + export RUSTUP_TOOLCHAIN="$RUST_TOOLCHAIN" +elif [ ! -f "$TOOLCHAIN_FILE" ]; then + die "rust-toolchain.toml missing; a pinned toolchain is required for reproducible builds." +fi + +RUST_VERSION="$(rustc --version)" +[ -n "$RUST_VERSION" ] || die "unable to determine rustc version." + +if ! rustup target list --installed 2>/dev/null | grep -q '^wasm32-unknown-unknown$'; then + die "wasm32-unknown-unknown target not installed. Run: rustup target add wasm32-unknown-unknown" +fi + +SDK_VERSION="$(grep -E '^soroban-sdk' "$CONTRACT_DIR/Cargo.toml" | head -n1 | sed -E 's/.*"([^"]+)".*/\1/')" +[ -n "$SDK_VERSION" ] || die "unable to determine soroban-sdk version from $CONTRACT_DIR/Cargo.toml" -echo "If you want this script to run the deploy step automatically, set AUTO_DEPLOY=1 in the environment." -if [ "${AUTO_DEPLOY:-0}" = "1" ]; then - echo "[escrow deploy] AUTO_DEPLOY=1 detected — running deployment now..." - soroban contract deploy --wasm "$WASM_PATH" +# --------------------------------------------------------------------------- +# 3. Source provenance +# --------------------------------------------------------------------------- +cd "$ROOT_DIR" +GIT_COMMIT="$(git rev-parse HEAD 2>/dev/null)" || die "not a git repository; cannot record source provenance." +GIT_TAG="$(git describe --tags --exact-match 2>/dev/null || echo "untagged")" +if [ -n "$(git status --porcelain -- contracts/escrow)" ]; then + die "uncommitted changes in contracts/escrow. Deploy only reviewed, committed source." fi -echo "\nDone. See docs/soroban-escrow-deployment.md for full instructions and examples." +# --------------------------------------------------------------------------- +# 4. Deterministic build +# --------------------------------------------------------------------------- +echo "[escrow deploy] Running contract tests..." +cd "$CONTRACT_DIR" +cargo test --locked || die "contract tests failed; deployment aborted." + +echo "[escrow deploy] Building escrow contract (locked, release, wasm32)..." +RUSTFLAGS="${RUSTFLAGS:-} --remap-path-prefix=$ROOT_DIR=." \ + cargo build --locked --release --target wasm32-unknown-unknown \ + || die "cargo build failed; deployment aborted." + +WASM_PATH="$CONTRACT_DIR/target/wasm32-unknown-unknown/release/escrow.wasm" +[ -f "$WASM_PATH" ] || die "WASM artifact not generated at $WASM_PATH" + +WASM_SHA256="$(sha256sum "$WASM_PATH" | awk '{print $1}')" +[ -n "$WASM_SHA256" ] || die "failed to compute WASM artifact hash." + +ARTIFACT_DIR="$RECORDS_DIR/artifacts/$WASM_SHA256" +mkdir -p "$ARTIFACT_DIR" +cp "$WASM_PATH" "$ARTIFACT_DIR/escrow.wasm" + +# --------------------------------------------------------------------------- +# 5. Initialization parameter validation +# --------------------------------------------------------------------------- +INIT_PARAMS_FILE="${ESCROW_INIT_PARAMS:-$ROOT_DIR/contracts/config/testnet.init.json}" +[ -f "$INIT_PARAMS_FILE" ] || die "initialization parameters file not found: $INIT_PARAMS_FILE" +if ! command -v jq >/dev/null 2>&1; then + die "jq is required to validate initialization parameters." +fi +jq -e '.network == "testnet" and (.admin | type == "string" and length > 0)' "$INIT_PARAMS_FILE" >/dev/null \ + || die "initialization parameters must declare network=testnet and a non-empty admin." +INIT_PARAMS="$(jq -c . "$INIT_PARAMS_FILE")" + +# --------------------------------------------------------------------------- +# 6. Deployment (opt-in) +# --------------------------------------------------------------------------- +TIMESTAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +RECORD_FILE="$RECORDS_DIR/escrow-${GIT_COMMIT:0:12}-${WASM_SHA256:0:12}.json" + +echo "[escrow deploy] Built WASM: $WASM_PATH" +echo "[escrow deploy] WASM sha256: $WASM_SHA256" + +if [ "${AUTO_DEPLOY:-0}" != "1" ]; then + echo "[escrow deploy] Build and validation complete. Set AUTO_DEPLOY=1 to deploy." + echo "[escrow deploy] Artifact archived at $ARTIFACT_DIR/escrow.wasm" + exit 0 +fi + +DEPLOY_OUT="$(mktemp)" +trap 'rm -f "$DEPLOY_OUT"' EXIT + +if ! soroban contract deploy \ + --wasm "$WASM_PATH" \ + --source "$SOROBAN_SOURCE_ACCOUNT" \ + --network "$EXPECTED_NETWORK" >"$DEPLOY_OUT" 2>&1; then + cat "$DEPLOY_OUT" >&2 + die "soroban contract deploy failed; no deployment record written." +fi + +CONTRACT_ID="$(grep -Eo 'C[A-Z2-7]{55}' "$DEPLOY_OUT" | tail -n1 || true)" +TX_HASH="$(grep -Eio '[0-9a-f]{64}' "$DEPLOY_OUT" | tail -n1 || true)" +[ -n "$CONTRACT_ID" ] || die "could not parse contract ID from deploy output; no record written." +[ -n "$TX_HASH" ] || die "could not parse deployment transaction hash; no record written." + +DEPLOYER_ADDRESS="$(soroban keys address "$SOROBAN_SOURCE_ACCOUNT" 2>/dev/null || echo "unknown")" + +# Post-deployment verification: the on-chain WASM must match the artifact hash. +echo "[escrow deploy] Verifying deployed contract against artifact..." +ONCHAIN_WASM="$(mktemp)" +trap 'rm -f "$DEPLOY_OUT" "$ONCHAIN_WASM"' EXIT +soroban contract fetch --id "$CONTRACT_ID" --network "$EXPECTED_NETWORK" --out-file "$ONCHAIN_WASM" >/dev/null 2>&1 \ + || die "failed to fetch deployed WASM for verification; deployment record not written." +ONCHAIN_SHA256="$(sha256sum "$ONCHAIN_WASM" | awk '{print $1}')" +[ "$ONCHAIN_SHA256" = "$WASM_SHA256" ] \ + || die "deployed WASM hash ($ONCHAIN_SHA256) does not match artifact ($WASM_SHA256)." + +# --------------------------------------------------------------------------- +# 7. Immutable deployment record (never overwritten) +# --------------------------------------------------------------------------- +mkdir -p "$RECORDS_DIR" +[ ! -e "$RECORD_FILE" ] || die "deployment record already exists: $RECORD_FILE (immutable)" + +TMP_RECORD="$(mktemp)" +jq -n \ + --arg network "$EXPECTED_NETWORK" \ + --arg contract_id "$CONTRACT_ID" \ + --arg wasm_sha256 "$WASM_SHA256" \ + --arg tx_hash "$TX_HASH" \ + --arg timestamp "$TIMESTAMP" \ + --arg git_commit "$GIT_COMMIT" \ + --arg git_tag "$GIT_TAG" \ + --arg rust_version "$RUST_VERSION" \ + --arg sdk_version "$SDK_VERSION" \ + --arg deployer "$DEPLOYER_ADDRESS" \ + --arg rpc_url "$SOROBAN_RPC_URL" \ + --argjson init_params "$INIT_PARAMS" \ + '{ + network: $network, + contract_id: $contract_id, + wasm_sha256: $wasm_sha256, + deployment_tx_hash: $tx_hash, + deployment_timestamp: $timestamp, + git_commit: $git_commit, + source_tag: $git_tag, + rust_toolchain: $rust_version, + soroban_sdk_version: $sdk_version, + deployer: $deployer, + rpc_url: $rpc_url, + initialization_params: $init_params, + verified_onchain_hash: true + }' > "$TMP_RECORD" || die "failed to write deployment record." + +mv "$TMP_RECORD" "$RECORD_FILE" +chmod 0444 "$RECORD_FILE" + +echo "[escrow deploy] Deployment complete." +echo "[escrow deploy] Contract ID: $CONTRACT_ID" +echo "[escrow deploy] Tx hash: $TX_HASH" +echo "[escrow deploy] Record: $RECORD_FILE" +echo "[escrow deploy] See docs/soroban-escrow-deployment.md for verification and redeployment steps." diff --git a/docs/DEPLOYMENT_GUIDE.md b/docs/DEPLOYMENT_GUIDE.md index 575c787..3ea6641 100644 --- a/docs/DEPLOYMENT_GUIDE.md +++ b/docs/DEPLOYMENT_GUIDE.md @@ -1,6 +1,6 @@ # TaskChain Mainnet Deployment Guide -**Version**: 1.0 +**Version**: 1.1 **Date**: 2026-06-24 **Status**: Draft @@ -10,6 +10,8 @@ This guide provides step-by-step instructions for deploying TaskChain to the Stellar mainnet. It covers pre-deployment preparation, the deployment process, post-deployment validation, and emergency procedures. +Smart contract deployments (Soroban escrow) must additionally follow the [Soroban Escrow Deployment Verification](#soroban-escrow-deployment-verification--reproducibility) procedures below, which define reproducible builds, artifact traceability, and auditable deployment records for both Testnet and Mainnet. + --- ## Prerequisites @@ -47,6 +49,7 @@ This guide provides step-by-step instructions for deploying TaskChain to the Ste ### 2. Smart Contract Preparation - [ ] Smart contract audited by reputable firm - [ ] Contract source code verified on Stellar explorer +- [ ] Build reproduced from pinned toolchain and WASM hash matches the recorded artifact - [ ] Contract deployed to mainnet - [ ] Contract tested on mainnet with small amounts - [ ] Emergency stop functionality tested @@ -67,6 +70,7 @@ This guide provides step-by-step instructions for deploying TaskChain to the Ste - [ ] ESCROW_ACCOUNT_ID set to platform escrow address - [ ] No testnet configuration in environment - [ ] Secrets stored in secure location (not in code) +- [ ] Network config (`config/networks/mainnet.env`) is separate from Testnet and contains no testnet values ### 5. Key Management - [ ] Platform escrow private key stored in HSM/KMS @@ -93,6 +97,7 @@ This guide provides step-by-step instructions for deploying TaskChain to the Ste ### 8. Testing - [ ] All unit tests passing - [ ] All integration tests passing +- [ ] CI contract test suite and build verification passing for the pinned toolchain - [ ] Load testing completed - [ ] Security testing completed - [ ] User acceptance testing completed diff --git a/docs/soroban-escrow-deployment.md b/docs/soroban-escrow-deployment.md index 22261fd..0b25dcc 100644 --- a/docs/soroban-escrow-deployment.md +++ b/docs/soroban-escrow-deployment.md @@ -56,6 +56,58 @@ Integration notes Replacing the JS stub - The repository contains a JS stub at `lib/soroban/deploy.ts`. Replace that stub with an implementation that uploads the compiled WASM, sends the install/create contract transaction, and returns the deployed contract ID and tx hash. See notes in that file for steps. +Reproducible deployment, verification, and audit records + +This section documents the reproducible deployment workflow required for Testnet and Mainnet. Authorized contributors should follow it end to end. + +Toolchain pinning +- Rust toolchain: pin the exact version in `rust-toolchain.toml` (for example `1.79.0`) with the `wasm32-unknown-unknown` target. +- Soroban SDK: pin the exact version in `contracts/contracts/escrow/Cargo.toml` and commit `Cargo.lock`. +- Record the versions used for every build in the deployment record. + +Build and artifact hashing +- Build from a clean checkout at a reviewed commit or tag. +- Compute the WASM artifact hash with `sha256sum contracts/contracts/escrow/target/wasm32-unknown-unknown/release/escrow.wasm`. +- Re-running the build from the same commit and toolchain must produce the same hash. If it does not, treat the build as non-reproducible and stop. + +Environment separation +- Testnet and Mainnet use separate configuration files (for example `deploy/testnet.env` and `deploy/mainnet.env`). Neither file may contain secrets. +- Secret keys are supplied only through environment variables or a secret manager and must never be committed to source control. +- Mainnet credentials must be distinct from Testnet credentials. +- Before deploying, confirm the configured network passphrase and RPC URL match the intended environment. Abort on mismatch. + +Initialization parameter validation +- Validate all initialization parameters (client, freelancer, arbiter, token address, milestone amounts) before submitting the transaction. +- After deployment, read back the contract state and compare it with the intended parameters. Abort and record the failure if they differ. + +Mainnet approval gate +- Mainnet deployment requires an explicit manual approval step, such as a protected GitHub Environment with required reviewers, before the deploy job runs. + +Deployment record +Each deployment appends a new immutable record. Do not overwrite earlier records. Store records under `deployments//.json` with these fields: +- Network name +- Contract ID +- WASM artifact hash +- Deployment transaction hash +- Deployment timestamp (UTC) +- Git commit hash and source tag/version +- Rust toolchain version +- Soroban SDK version +- Initialization parameters +- Deployer account/address + +Incomplete records must not be written. If any step fails, the workflow emits an actionable error message and writes nothing. + +Verification +- Anyone can confirm a deployment by rebuilding from the recorded commit and toolchain, comparing the WASM hash to the recorded hash, and checking the on-chain contract ID and deployment transaction hash against the record. + +CI requirements +- CI builds with the pinned toolchain and runs the full contract test suite. +- CI blocks deployment if tests fail, build verification fails, required configuration values are missing, or artifact generation is unsuccessful. + +Redeployment +- Redeploying creates a new deployment record. Historical records are preserved. + Further reading - Soroban RPC & CLI docs: https://soroban.stellar.org - Soroban developer docs: https://soroban.stellar.org/docs diff --git a/env.example b/env.example index ce0bc56..cf6f6ed 100644 --- a/env.example +++ b/env.example @@ -17,6 +17,20 @@ STELLAR_HORIZON_URL=https://horizon-testnet.stellar.org # Soroban JSON-RPC endpoint used for contract transaction confirmation. SOROBAN_RPC_URL=https://soroban-testnet.stellar.org +# Deployment environment. Must be "testnet" or "mainnet". +# Deployment scripts refuse to run if this does not match STELLAR_NETWORK_PASSPHRASE. +STELLAR_NETWORK=testnet + +# Pinned Rust toolchain used to build the escrow contract (must match rust-toolchain.toml). +ESCROW_RUST_TOOLCHAIN=1.84.0 + +# Pinned Soroban SDK version used by the escrow contract (must match Cargo.toml). +ESCROW_SOROBAN_SDK_VERSION=21.7.0 + +# Stellar account (secret key, S...) used to deploy the escrow contract. +# Never commit a real value. Use a separate key for Testnet and Mainnet. +# DEPLOYER_SECRET_KEY=S... + # Explorer transaction prefix; change to /public/tx for mainnet. STELLAR_EXPLORER_TX_URL=https://stellar.expert/explorer/testnet/tx @@ -34,6 +48,14 @@ STELLAR_NETWORK_PASSPHRASE=Test SDF Network ; September 2015 # Platform escrow account (Stellar public key) used by the worker. ESCROW_ACCOUNT_ID=G... +# Directory where deployment records (JSON) are written. Records are append-only. +# Defaults to /deployments if not set. +# DEPLOYMENT_RECORDS_DIR=/data/taskchain/deployments + +# Required manual approval token for Mainnet deployments. Set only in the +# approval-gated CI environment; never in Testnet configuration. +# MAINNET_DEPLOY_APPROVAL= + # ─── File Upload (Milestone Deliverables) ────────────────────────────────────── # 32-byte hex key used to encrypt deliverable files at rest. # Generate one with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"