From 2c9565a9fbfd17cbeb33dce2ec2701a5ccf72cba Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Sat, 24 Oct 2026 15:36:56 +0200 Subject: [PATCH] ci(testnet): reproduce the contract state divergence with a dice contract Dice reads its own balance and pays 10 CS when it holds at least 20: a node re-executing it while it syncs sees the balance after the same block's payout, throws, keeps a stale state and charges a later payout's fee to the previous player. contracts.py --dice (run.sh CONTRACT_DICE=1) deploys it, funds it, and has two players play it three times in turn before the restart test; its state is compared on every node. Scenario contracts-dice-join (manual): a node syncs from block 0 through the plays. It is expected to fail until contract states are fetched instead of re-executed (step 0 of the contract state sync plan). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/robustness.yml | 7 +++ ci/testnet/contracts.py | 77 +++++++++++++++++++++++++++++++- ci/testnet/run.sh | 5 ++- 3 files changed, 87 insertions(+), 2 deletions(-) diff --git a/.github/workflows/robustness.yml b/.github/workflows/robustness.yml index 094d542cf..f4e53e5ec 100644 --- a/.github/workflows/robustness.yml +++ b/.github/workflows/robustness.yml @@ -276,6 +276,13 @@ jobs: env: DB_BACKEND=berkeleydb CONVERT_AT=1500 TARGET_SEQ=2500 # smart contracts (each node with its executor, contracts.py through n1) across the faults: # six SIGKILLs of n6 and its executor while contracts are deployed and called + # reproduction of the contract state divergence (docs/specs/2026-10-24-contract-state-sync-design.md): + # a node that syncs from block 0 through plays of a contract reading its own balance; fails + # until contract states are fetched instead of re-executed + - name: contracts-dice-join + env: DB_BACKEND=lmdb CONTRACTS=1 CONTRACT_DICE=1 JOIN_PRUNED_AT=500 JOIN_FULL=1 CONTRACTS_AFTER_AT=700 TARGET_SEQ=1300 + contracts: true + manual: true - name: contracts-crash env: DB_BACKEND=lmdb CRASH_NODE=6 CONTRACTS=1 TARGET_SEQ=1600 contracts: true diff --git a/ci/testnet/contracts.py b/ci/testnet/contracts.py index 79ab65ddf..25865b733 100644 --- a/ci/testnet/contracts.py +++ b/ci/testnet/contracts.py @@ -114,6 +114,44 @@ } """ +# a game that reads its own balance, as the mainnet dice contracts do: executed live it sees the +# balance before its payout; a node re-executing it while it syncs sees the balance after the payout +# of the same block, throws, keeps a stale state, and charges the fee of a later payout to the +# previous player (docs/specs/2026-10-24-contract-state-sync-design.md, 4.2) +DICE = """import com.credits.scapi.v3.SmartContract; + +import java.math.BigDecimal; + +public class Dice extends SmartContract { + private int plays; + private String lastPlayer; + + public Dice() { + super(); + } + + public int play() { + BigDecimal balance = getBalance(contractAddress); + if (balance.compareTo(new BigDecimal("20")) < 0) { + throw new RuntimeException("insufficient balance " + balance); + } + sendTransaction(contractAddress, initiator, 10.0, new byte[0]); + plays += 1; + lastPlayer = initiator; + return plays; + } + + public int plays() { + return plays; + } + + @Override + public String payable(BigDecimal amount, byte[] userData) { + return "ok"; + } +} +""" + # no @UsingContract: the node refuses any call to a method that declares one (Violations::SubsequentCall, # checked by the API and by IterValidator), so the call is a plain invokeExternalContract CALLER = """import com.credits.scapi.v0.SmartContract; @@ -167,6 +205,8 @@ def write_sources(directory): f.write(CALLER_DECLARED % (placeholder, placeholder)) with open(os.path.join(directory, "Ledger.java"), "w") as f: f.write(LEDGER) + with open(os.path.join(directory, "Dice.java"), "w") as f: + f.write(DICE) def invocation(method="", used=(), deploy=None): @@ -270,6 +310,35 @@ def deploy(client, master, name, source): sys.exit(f"{name} not deployed after 300 s") +def dice_plays(client_for, master, dice): + """25 CS into the contract, then three plays by two players in turn, each followed by a 10 CS + top-up from the master. Returns the number of failures.""" + funder = Client(9090, 300) + players = [Account(hashlib.sha256(master.pk + b"dice player %d" % i).digest()) for i in (1, 2)] + master.next_inner_id = None + for p in players: + ok, message = send(funder, master, p.pk, 100) + print(f"Dice: fund player {base58.b58encode(p.pk).decode()[:8]}: {'ok' if ok else 'FAILED ' + str(message)}", flush=True) + ok, message = send(funder, master, dice, 25) + print(f"Dice: 25 CS to the contract: {'ok' if ok else 'FAILED ' + str(message)}", flush=True) + deadline = time.time() + 300 + while time.time() < deadline and (balance(funder, dice) < 25 or any(balance(funder, p.pk) < 100 for p in players)): + time.sleep(5) + print(f"Dice: contract balance {balance(funder, dice)}", flush=True) + failures = 0 + for n in range(3): + player = players[n % 2] + failures += 0 if call(client_for(1), player, dice, "play", f"Dice play {n + 1} by player {n % 2 + 1}", n + 1) else 1 + master.next_inner_id = None + before = balance(funder, dice) + ok, message = send(funder, master, dice, 10) + deadline = time.time() + 120 + while time.time() < deadline and balance(funder, dice) < before + 10: + time.sleep(3) + print(f"Dice: top-up after play {n + 1}: {'ok' if ok else 'FAILED ' + str(message)}, contract balance {balance(funder, dice)}", flush=True) + return failures + + def call(client, master, contract, method, label, expected=None): deadline = time.time() + 120 while True: @@ -426,6 +495,8 @@ def main(): parser.add_argument("--stats-file", default="") # nodes left out of the reads (still compared at the end) parser.add_argument("--skip-read-nodes", default="") + parser.add_argument("--dice", action="store_true", + help="deploy Dice and play it before the restart (a contract whose re-execution is not reproducible)") args = parser.parse_args() check_nodes = args.check_nodes or args.nodes skipped = {int(n) for n in args.skip_read_nodes.split() if n.strip()} @@ -447,6 +518,7 @@ def client_for(i): # contract-to-contract calls fail on mainnet today; what matters is that every node fails them the # same way, also a node that restarted from a checkpoint taken after the callee was deployed callers = (("Caller", caller), ("CallerDeclared", declared)) + dice = deploy(client_for(1), master, "Dice", DICE) if args.dice else None def call_callers(when, via): for name, contract in callers: @@ -487,6 +559,9 @@ def one(i): print(f" n{i}: {v!r} {msg!r}", flush=True) return len(bad) + if dice: + failures += dice_plays(client_for, master, dice) + failures += read_all(dice, "plays", 3, "Dice.plays") failures += read_all(counter, "get", calls, "Counter.get before restart") failures += read_all(ledger, "entries", calls, "Ledger.entries before restart") @@ -551,7 +626,7 @@ def footprint(): time.sleep(5) print(f"final file {'found' if os.path.exists(args.final_file) else 'MISSING'}", flush=True) time.sleep(60) # let the last state reach every node - for name, contract in (("Counter", counter), ("Ledger", ledger)) + callers: + for name, contract in (("Counter", counter), ("Ledger", ledger)) + callers + ((("Dice", dice),) if dice else ()): states = {} for i in range(1, (args.check_nodes or args.nodes) + 1): try: diff --git a/ci/testnet/run.sh b/ci/testnet/run.sh index 508a8b32d..62e3040a7 100755 --- a/ci/testnet/run.sh +++ b/ci/testnet/run.sh @@ -34,6 +34,8 @@ # node reached CONTRACTS_AFTER_AT (default 0); the states are compared once every node, # a joining one too, reached TARGET_SEQ. contracts.py sends everything through n1: a # contract scenario never kills, partitions or slows n1 +# CONTRACT_DICE=1 (with CONTRACTS): also a Dice contract that reads its own balance, played three +# times before the restart test; a node that syncs through the plays re-executes them # CONTRACT_LOAD_SECONDS (default 0, with CONTRACTS): after the calls, a load phase of that many # seconds: CONTRACT_WRITE_RATE (default 1) Counter.next writes a second from every node's # account through its own API, and CONTRACT_READ_RATE (default 5) Counter.get reads (getters, @@ -175,6 +177,7 @@ SYNCRO_ROUND=${SYNCRO_ROUND:-0} JOIN_FULL=${JOIN_FULL:-0} CONTRACTS=${CONTRACTS:-0} CONTRACTS_AFTER_AT=${CONTRACTS_AFTER_AT:-0} +CONTRACT_DICE=${CONTRACT_DICE:-0} [ "$CONTRACTS_AFTER_AT" -eq 0 ] || [ "$CONTRACTS_AFTER_AT" -le $(( ${TARGET_SEQ:-1100} - 100 )) ] \ || { echo "CONTRACTS_AFTER_AT must be at most TARGET_SEQ - 100"; exit 1; } PRUNE_NODE=${PRUNE_NODE:-0} @@ -970,7 +973,7 @@ PY --ready-file "$WORK/contracts-ready" --wait-file "$WORK/restart-done" --wait-timeout $((TIMEOUT_MIN * 60)) \ --check-nodes "$ALL_NODES" --final-file "$WORK/contracts-final" \ --load-seconds "$CONTRACT_LOAD_SECONDS" --write-rate "$CONTRACT_WRITE_RATE" --read-rate "$CONTRACT_READ_RATE" \ - --stats-file "$WORK/contracts-stats.json") > "$WORK/contracts.log" 2>&1 & + --stats-file "$WORK/contracts-stats.json" $([ "$CONTRACT_DICE" = 1 ] && echo --dice)) > "$WORK/contracts.log" 2>&1 & CONTRACTS_PID=$! fi # contracts.py ended before its first calls were done: nothing would release the restart test