AOSSIE-Org / AOSSIE-Org/Agora-Blockchain
BUG: removeCandidate leaves stale candidateID on swapped candidate after swap-and-pop
- Dominant language
- JavaScript
- Stars
- 97
- Forks
- 199
- PR merge metrics
- No merged PRs in 30d
Description
### Is there an existing issue for this?
- [x] I have searched the existing issues
### Issue Description ✍️
## 📌 Describe the Bug
Election.removeCandidate() uses a swap-and-pop pattern to remove a candidate by
index — it copies the last element into the deleted slot, then pops the array.
However, it never updates the `candidateID` field of the moved candidate.
After the swap, the candidate sitting at index `_id` still carries its old
`candidateID` from its original position, making the `candidateID` field
inconsistent with the candidate's actual position in the array.
## 🚨 Actual Behavior
Given 3 candidates initialized as:
candidates[0] = Candidate { candidateID: 0, name: "Alice" }
candidates[1] = Candidate { candidateID: 1, name: "Bob" }
candidates[2] = Candidate { candidateID: 2, name: "Carol" }.
After calling removeCandidate(0);
candidates[0] = Candidate { candidateID: 2, name: "Carol" } // ID is 2, should be 0
candidates[1] = Candidate { candidateID: 1, name: "Bob" }.
Carol is now at index `0` but her `candidateID` is still `2`. Any frontend or
contract logic that reads `candidateID` to identify a candidate's position will
silently receive wrong data. This also breaks the invariant that
`candidates[i].candidateID == i`, which the `initialize()` function explicitly
establishes when building the candidates array.
## 🎯 Expected Behavior
After `removeCandidate(0)`, the moved candidate's `candidateID` should be updated
to reflect its new position:
candidates[0] = Candidate { candidateID: 0, name: "Carol" } // ID updated
candidates[1] = Candidate { candidateID: 1, name: "Bob" }
The invariant `candidates[i].candidateID == i` must hold at all times.
## 💡 Suggestions
update `candidateID` immediately after the swap, before the pop.
### Record
- [x] I have synced all my node versions as mentioned in the project
- [x] I am using the same version of npm as is the project
- [x] My current branch is in sync with the development branch
- [x] I want to work on this issue
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.