What happens when a player never reveals? How to set deadlines, punish walking away, and avoid the encoding bug that silently breaks most first attempts. With a tested example contract.
The problem
Commit-reveal is the standard way to let several people pick a value without anyone seeing the others’ picks first: rock-paper-scissors, sealed bids, a shared random number. It runs in two phases:
- Commit. Each player submits
hash(secret value + salt). Nobody can read the value from the hash. - Reveal. Each player sends the value and the salt. The contract recomputes the hash and checks it matches.
The hard part sits between the two phases. A contract cannot force anyone to reveal. If the round waits for every player, a single player who goes offline blocks it forever. Worse, the player who reveals last has already seen everyone else’s values. If they see they are losing, they have every reason to simply not reveal.
So a commit-reveal contract needs three things:
- a deadline after which the round can end without the missing reveals;
- a cost for not revealing, so that quitting is never the winning move;
- a way to settle the round that nobody can block.
Time in the Klever VM
The VM never runs code on its own at a given time. There are no timers and no scheduled calls. A deadline is a value the contract stores when the round starts and checks the next time someone calls it.
The SDK gives you several clocks through self.blockchain():
| Getter | What it returns | Use it for deadlines? |
|---|---|---|
get_block_timestamp() |
The block’s Unix timestamp, in seconds | Yes. See below |
get_block_round() |
The slot number | Possible. It advances with time, but it is less readable |
get_block_nonce() |
How many blocks have been committed | No |
Why the timestamp is reliable. A node only accepts a block whose timestamp falls inside that block’s slot window: genesis + slot × 4 s up to 4 s later. The block proposer can move it by at most one slot. For deadlines measured in minutes, that drift does not matter.
Why the nonce is a trap. The nonce counts blocks that were actually produced. Every missed slot makes it fall behind real time, and if the chain pauses, the nonce stops altogether. A deadline of “nonce + 150” is therefore not “10 minutes from now”. It stretches by however many blocks the network misses, which is exactly when you least want surprises.
One caveat for off-chain checks. When you query a view (not a transaction), the VM uses the last committed block’s timestamp. A front-end that asks “has the deadline passed?” through a view can be a few seconds behind. Treat the on-chain check inside the transaction as the only one that counts.
The pattern
The example contract runs rounds like this:
createRound(commit_secs, reveal_secs, bond, max_players)stores absolute deadlines:commit_deadline = now + commit_secs,reveal_deadline = commit_deadline + reveal_secs.commit(round_id, hash)takes exactly the bond in KLV, during the commit phase only.reveal(round_id, value, salt)is accepted only between the two deadlines.- After
reveal_deadline, anyone can callfinalize(round_id). Players who revealed get their bond back plus an equal share of the bonds of the players who did not reveal. - Each player withdraws with
claim().
The phase boundaries are exact, with no gap and no overlap:
// commit
require!(now < round.commit_deadline, "commit phase over");
// reveal
require!(
round.commit_deadline <= now && now < round.reveal_deadline,
"not in reveal phase"
);
// finalize
require!(now >= round.reveal_deadline, "too early");
The tests check each boundary with a pair of calls one second apart, one accepted and one rejected. Changing any < to <= (or >= to >) makes them fail.
Why a bond, and why split it among the revealers
The bond is what makes the last-revealer problem go away. A player who does not reveal loses their bond, and the players who did reveal receive it. Quitting now costs money, and it pays the honest players.
When you size the bond, make it worth more than anything a player could gain by aborting. If a round’s prize is larger than the bond, a losing player can still prefer to walk away. The bond is the only deterrent the contract has.
Splitting the forfeited bonds among revealers is deliberate. Sending them to the contract owner would give the owner a reason to want players to fail.
Integer division leaves a remainder. The example gives it to the first revealer in commit order, so not a single unit stays locked in the contract:
let share = &forfeit_total / &revealers;
let mut remainder = &forfeit_total % &revealers;
for player in players.iter() {
if self.has_revealed(round_id, &player) {
let payout = &round.bond + &share + &remainder;
remainder = BigUint::zero();
self.credit(&player, &payout);
}
}
If nobody reveals, the whole pot is credited to the contract owner. That is a design choice for the example; your contract might refund everyone or burn it instead.
Why finalize is open to anyone, and payouts are pulled
If only the owner could settle a round, the owner could stall it. Because anyone can call finalize once the deadline has passed, the round always ends.
finalize does not send KLV to every player. It only credits a claimable balance, and each player pulls their own with claim(). Sending to many addresses in one transaction is how contracts run out of gas or hit per-transaction transfer limits. The example also caps a round at 100 players, so the loop inside finalize has a known upper bound.
claim clears the balance before sending, so the same balance can never be paid twice:
let amount = self.claimable(&caller).get();
require!(amount > 0u32, "nothing to claim");
self.claimable(&caller).clear();
self.send().direct_klv(&caller, &amount);
The bug that breaks most first attempts: an ambiguous commitment
The obvious commitment is keccak256(value ‖ salt), and to stop copying, keccak256(value ‖ salt ‖ caller). Our own first draft of this example did exactly that, with a salt of “at least 32 bytes”. It is broken.
The hash only sees a stream of bytes. Nothing in it says where value ends and salt begins. Take a commitment to "rock" with salt S:
value = "rock" salt = S → bytes: r o c k S…
value = "roc" salt = "k" + S → bytes: r o c k S… (same hash)
value = "r" salt = "ock" + S → bytes: r o c k S… (same hash)
All three reveals pass the hash check. In rock-paper-scissors that sounds harmless, but in a sealed-bid auction or a random-number round it is fatal. An attacker commits to a carefully chosen byte string, waits to see everyone else’s reveal, and then picks whichever cut of those bytes wins. The commitment no longer commits to anything.
A second, quieter problem: if the hash does not include the round, the same commitment is valid in every round. A player who reveals in one round publishes a value that is still a valid commitment in another round that is still taking commits.
The fix is to give every field a fixed length except the last one, and to bind the hash to the round and the contract:
round_id 8 bytes, big-endian u64
contract 32 bytes, the contract address
player 32 bytes, the caller
salt exactly 32 bytes
value the rest
fn compute_commitment(
&self,
round_id: u64,
player: &ManagedAddress,
salt: &ManagedByteArray<Self::Api, SALT_LEN>,
value: &ManagedBuffer,
) -> ManagedByteArray<Self::Api, 32> {
let mut preimage = ManagedBuffer::new_from_bytes(&round_id.to_be_bytes());
preimage.append(self.blockchain().get_sc_address().as_managed_buffer());
preimage.append(player.as_managed_buffer());
preimage.append(salt.as_managed_buffer());
preimage.append(value);
self.crypto().keccak256(&preimage)
}
Now the bytes can only be split one way. The salt is a ManagedByteArray<32>, so a salt of any other length is rejected before the endpoint even runs. The round id, the contract address and the player make each commitment valid in exactly one place.
The example’s tests include the "roc" + "k…" attack (now rejected) and a commitment replayed in a second round (now rejected).
Keep the salt secret and random. Use 32 random bytes per round, and never reuse a salt. Without a strong salt, anyone can try every possible value (there are only three moves in rock-paper-scissors) and read your commitment before you reveal.
Compute the commitment locally. The example exposes a computeCommitment view that returns the same hash, for tests and tooling. But a view takes the secret as input: querying it sends your value and salt to whichever node answers. Calling it as a transaction would publish them on-chain. For real use, compute the hash in your client with the layout above.
Other pitfalls
- Phases that are too short. Blocks are 4 seconds apart, and slots can be missed. A 10-second reveal window can close before a player’s transaction is ever included. The example enforces at least 60 seconds (15 blocks) per phase. Real games usually want minutes, not seconds.
- Overflow in deadline maths. The wasm release build does not trap on integer overflow.
now + huge_valuecan wrap around and produce a deadline in the past. A round could then be finalized and still accept commits, locking those bonds. Usechecked_addand reject the round if it overflows. - An empty value. If “not revealed” is stored as an empty value, an empty reveal looks like no reveal, and the player loses their bond for revealing. The example rejects empty values.
- Storage that is never cleaned up. After
finalize, the example clears the commitments, the revealed values and the player list. It keeps only the round’s settings, so a secondfinalizeis refused. - Who you are trusting. The example contract has an upgrade endpoint, and it sends the no-reveal pot to whoever owns the contract when
finalizeruns. The first is by far the bigger trust assumption: deployed as upgradeable, the owner can replace the code and take every bond the contract holds. Deploy non-upgradeable for real use, and say plainly to your users what the owner can do. - Rounds that never end. Without an upper bound, anyone could open a round whose reveal deadline is centuries away and lock every bond committed to it. The example caps each phase at 30 days. Players should still read the round’s deadlines before they commit.
- Several seats, one player. Because forfeited bonds go to the revealers, a player who holds several addresses in one round gets back part of the bond their own address forfeits. With two of three seats, withholding one reveal costs half a bond, not a whole one. If that matters, send forfeits somewhere no player controls, such as a burn or a treasury.
- Open rounds. In the example, anyone can create a round and anyone can join it. A party that fills every seat and never reveals blocks everyone else, and if that party is the contract owner, the no-reveal pot comes straight back to them. If that matters, restrict who may commit, for example with an allowlist set by the round’s creator.
- Censorship near the deadline. A reveal only counts if a block includes it in time. A validator who also plays could leave other players’ reveals out of the last blocks and collect their bonds. For rounds with real value, use a reveal phase of several minutes and reveal early.
- Defense in depth. Timestamps never move backwards on a real chain, so a commit can never arrive after
finalize. The example still refusescommitandrevealon a finalized round, because a bond accepted after settlement could never be paid out. A one-line check is cheap insurance.
Testing deadlines
Scenario tests move the clock with setState:
{
"step": "setState",
"currentBlockInfo": { "blockTimestamp": "1600" }
}
The example has 15 scenarios, and each one runs on both the Rust VM and the Go VM. They cover:
- every deadline boundary;
- a missing reveal and the split of its bond, including an odd remainder;
- a round where nobody reveals;
- double claims and double finalize;
- wrong, zero and non-KLV payments;
- a full round;
- the ambiguous-split attack;
- a cross-round replay.
Get the code
The full contract, its scenarios and how to run them: commit-reveal example, klever-vm-sdk-rs.
cargo test -p commit-reveal
cargo test -p commit-reveal --features klever-sc-scenario/run-go-tests # needs `operator` on PATH
Not covered here: on-chain randomness beacons and native timers. If you build something on top of this pattern, share it in the forum. We would like to see it.
