snapshot_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package backend
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "math/big"
  21. "reflect"
  22. "testing"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/consensus/istanbul"
  25. istanbulcommon "github.com/ethereum/go-ethereum/consensus/istanbul/common"
  26. qbftengine "github.com/ethereum/go-ethereum/consensus/istanbul/qbft/engine"
  27. "github.com/ethereum/go-ethereum/consensus/istanbul/testutils"
  28. "github.com/ethereum/go-ethereum/consensus/istanbul/validator"
  29. "github.com/ethereum/go-ethereum/core/rawdb"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. )
  33. type testerVote struct {
  34. validator string
  35. voted string
  36. auth bool
  37. }
  38. // testerAccountPool is a pool to maintain currently active tester accounts,
  39. // mapped from textual names used in the tests below to actual Ethereum private
  40. // keys capable of signing transactions.
  41. type testerAccountPool struct {
  42. accounts map[string]*ecdsa.PrivateKey
  43. }
  44. func newTesterAccountPool() *testerAccountPool {
  45. return &testerAccountPool{
  46. accounts: make(map[string]*ecdsa.PrivateKey),
  47. }
  48. }
  49. func (ap *testerAccountPool) writeValidatorVote(header *types.Header, validator string, recipientAddress string, authorize bool) error {
  50. return qbftengine.ApplyHeaderQBFTExtra(
  51. header,
  52. qbftengine.WriteVote(ap.address(recipientAddress), authorize),
  53. )
  54. }
  55. func (ap *testerAccountPool) address(account string) common.Address {
  56. // Ensure we have a persistent key for the account
  57. if ap.accounts[account] == nil {
  58. ap.accounts[account], _ = crypto.GenerateKey()
  59. }
  60. // Resolve and return the Ethereum address
  61. return crypto.PubkeyToAddress(ap.accounts[account].PublicKey)
  62. }
  63. // Tests that voting is evaluated correctly for various simple and complex scenarios.
  64. func TestVoting(t *testing.T) {
  65. // Define the various voting scenarios to test
  66. tests := []struct {
  67. epoch uint64
  68. validators []string
  69. votes []testerVote
  70. results []string
  71. }{
  72. {
  73. // Single validator, no votes cast
  74. validators: []string{"A"},
  75. votes: []testerVote{{validator: "A"}},
  76. results: []string{"A"},
  77. }, {
  78. // Single validator, voting to add two others (only accept first, second needs 2 votes)
  79. validators: []string{"A"},
  80. votes: []testerVote{
  81. {validator: "A", voted: "B", auth: true},
  82. {validator: "B"},
  83. {validator: "A", voted: "C", auth: true},
  84. },
  85. results: []string{"A", "B"},
  86. }, {
  87. // Two validators, voting to add three others (only accept first two, third needs 3 votes already)
  88. validators: []string{"A", "B"},
  89. votes: []testerVote{
  90. {validator: "A", voted: "C", auth: true},
  91. {validator: "B", voted: "C", auth: true},
  92. {validator: "A", voted: "D", auth: true},
  93. {validator: "B", voted: "D", auth: true},
  94. {validator: "C"},
  95. {validator: "A", voted: "E", auth: true},
  96. {validator: "B", voted: "E", auth: true},
  97. },
  98. results: []string{"A", "B", "C", "D"},
  99. }, {
  100. // Single validator, dropping itself (weird, but one less cornercase by explicitly allowing this)
  101. validators: []string{"A"},
  102. votes: []testerVote{
  103. {validator: "A", voted: "A", auth: false},
  104. },
  105. results: []string{},
  106. }, {
  107. // Two validators, actually needing mutual consent to drop either of them (not fulfilled)
  108. validators: []string{"A", "B"},
  109. votes: []testerVote{
  110. {validator: "A", voted: "B", auth: false},
  111. },
  112. results: []string{"A", "B"},
  113. }, {
  114. // Two validators, actually needing mutual consent to drop either of them (fulfilled)
  115. validators: []string{"A", "B"},
  116. votes: []testerVote{
  117. {validator: "A", voted: "B", auth: false},
  118. {validator: "B", voted: "B", auth: false},
  119. },
  120. results: []string{"A"},
  121. }, {
  122. // Three validators, two of them deciding to drop the third
  123. validators: []string{"A", "B", "C"},
  124. votes: []testerVote{
  125. {validator: "A", voted: "C", auth: false},
  126. {validator: "B", voted: "C", auth: false},
  127. },
  128. results: []string{"A", "B"},
  129. }, {
  130. // Four validators, consensus of two not being enough to drop anyone
  131. validators: []string{"A", "B", "C", "D"},
  132. votes: []testerVote{
  133. {validator: "A", voted: "C", auth: false},
  134. {validator: "B", voted: "C", auth: false},
  135. },
  136. results: []string{"A", "B", "C", "D"},
  137. }, {
  138. // Four validators, consensus of three already being enough to drop someone
  139. validators: []string{"A", "B", "C", "D"},
  140. votes: []testerVote{
  141. {validator: "A", voted: "D", auth: false},
  142. {validator: "B", voted: "D", auth: false},
  143. {validator: "C", voted: "D", auth: false},
  144. },
  145. results: []string{"A", "B", "C"},
  146. }, {
  147. // Authorizations are counted once per validator per target
  148. validators: []string{"A", "B"},
  149. votes: []testerVote{
  150. {validator: "A", voted: "C", auth: true},
  151. {validator: "B"},
  152. {validator: "A", voted: "C", auth: true},
  153. {validator: "B"},
  154. {validator: "A", voted: "C", auth: true},
  155. },
  156. results: []string{"A", "B"},
  157. }, {
  158. // Authorizing multiple accounts concurrently is permitted
  159. validators: []string{"A", "B"},
  160. votes: []testerVote{
  161. {validator: "A", voted: "C", auth: true},
  162. {validator: "B"},
  163. {validator: "A", voted: "D", auth: true},
  164. {validator: "B"},
  165. {validator: "A"},
  166. {validator: "B", voted: "D", auth: true},
  167. {validator: "A"},
  168. {validator: "B", voted: "C", auth: true},
  169. },
  170. results: []string{"A", "B", "C", "D"},
  171. }, {
  172. // Deauthorizations are counted once per validator per target
  173. validators: []string{"A", "B"},
  174. votes: []testerVote{
  175. {validator: "A", voted: "B", auth: false},
  176. {validator: "B"},
  177. {validator: "A", voted: "B", auth: false},
  178. {validator: "B"},
  179. {validator: "A", voted: "B", auth: false},
  180. },
  181. results: []string{"A", "B"},
  182. }, {
  183. // Deauthorizing multiple accounts concurrently is permitted
  184. validators: []string{"A", "B", "C", "D"},
  185. votes: []testerVote{
  186. {validator: "A", voted: "C", auth: false},
  187. {validator: "B"},
  188. {validator: "C"},
  189. {validator: "A", voted: "D", auth: false},
  190. {validator: "B"},
  191. {validator: "C"},
  192. {validator: "A"},
  193. {validator: "B", voted: "D", auth: false},
  194. {validator: "C", voted: "D", auth: false},
  195. {validator: "A"},
  196. {validator: "B", voted: "C", auth: false},
  197. },
  198. results: []string{"A", "B"},
  199. }, {
  200. // Votes from deauthorized validators are discarded immediately (deauth votes)
  201. validators: []string{"A", "B", "C"},
  202. votes: []testerVote{
  203. {validator: "C", voted: "B", auth: false},
  204. {validator: "A", voted: "C", auth: false},
  205. {validator: "B", voted: "C", auth: false},
  206. {validator: "A", voted: "B", auth: false},
  207. },
  208. results: []string{"A", "B"},
  209. }, {
  210. // Votes from deauthorized validators are discarded immediately (auth votes)
  211. validators: []string{"A", "B", "C"},
  212. votes: []testerVote{
  213. {validator: "C", voted: "B", auth: false},
  214. {validator: "A", voted: "C", auth: false},
  215. {validator: "B", voted: "C", auth: false},
  216. {validator: "A", voted: "B", auth: false},
  217. },
  218. results: []string{"A", "B"},
  219. }, {
  220. // Cascading changes are not allowed, only the the account being voted on may change
  221. validators: []string{"A", "B", "C", "D"},
  222. votes: []testerVote{
  223. {validator: "A", voted: "C", auth: false},
  224. {validator: "B"},
  225. {validator: "C"},
  226. {validator: "A", voted: "D", auth: false},
  227. {validator: "B", voted: "C", auth: false},
  228. {validator: "C"},
  229. {validator: "A"},
  230. {validator: "B", voted: "D", auth: false},
  231. {validator: "C", voted: "D", auth: false},
  232. },
  233. results: []string{"A", "B", "C"},
  234. }, {
  235. // Changes reaching consensus out of bounds (via a deauth) execute on touch
  236. validators: []string{"A", "B", "C", "D"},
  237. votes: []testerVote{
  238. {validator: "A", voted: "C", auth: false},
  239. {validator: "B"},
  240. {validator: "C"},
  241. {validator: "A", voted: "D", auth: false},
  242. {validator: "B", voted: "C", auth: false},
  243. {validator: "C"},
  244. {validator: "A"},
  245. {validator: "B", voted: "D", auth: false},
  246. {validator: "C", voted: "D", auth: false},
  247. {validator: "A"},
  248. {validator: "C", voted: "C", auth: true},
  249. },
  250. results: []string{"A", "B"},
  251. }, {
  252. // Changes reaching consensus out of bounds (via a deauth) may go out of consensus on first touch
  253. validators: []string{"A", "B", "C", "D"},
  254. votes: []testerVote{
  255. {validator: "A", voted: "C", auth: false},
  256. {validator: "B"},
  257. {validator: "C"},
  258. {validator: "A", voted: "D", auth: false},
  259. {validator: "B", voted: "C", auth: false},
  260. {validator: "C"},
  261. {validator: "A"},
  262. {validator: "B", voted: "D", auth: false},
  263. {validator: "C", voted: "D", auth: false},
  264. {validator: "A"},
  265. {validator: "B", voted: "C", auth: true},
  266. },
  267. results: []string{"A", "B", "C"},
  268. }, {
  269. // Ensure that pending votes don't survive authorization status changes. This
  270. // corner case can only appear if a validator is quickly added, remove and then
  271. // readded (or the inverse), while one of the original voters dropped. If a
  272. // past vote is left cached in the system somewhere, this will interfere with
  273. // the final validator outcome.
  274. validators: []string{"A", "B", "C", "D", "E"},
  275. votes: []testerVote{
  276. {validator: "A", voted: "F", auth: true}, // Authorize F, 3 votes needed
  277. {validator: "B", voted: "F", auth: true},
  278. {validator: "C", voted: "F", auth: true},
  279. {validator: "D", voted: "F", auth: false}, // Deauthorize F, 4 votes needed (leave A's previous vote "unchanged")
  280. {validator: "E", voted: "F", auth: false},
  281. {validator: "B", voted: "F", auth: false},
  282. {validator: "C", voted: "F", auth: false},
  283. {validator: "D", voted: "F", auth: true}, // Almost authorize F, 2/3 votes needed
  284. {validator: "E", voted: "F", auth: true},
  285. {validator: "B", voted: "A", auth: false}, // Deauthorize A, 3 votes needed
  286. {validator: "C", voted: "A", auth: false},
  287. {validator: "D", voted: "A", auth: false},
  288. {validator: "B", voted: "F", auth: true}, // Finish authorizing F, 3/3 votes needed
  289. },
  290. results: []string{"B", "C", "D", "E", "F"},
  291. }, {
  292. // Epoch transitions reset all votes to allow chain checkpointing
  293. epoch: 3,
  294. validators: []string{"A", "B"},
  295. votes: []testerVote{
  296. {validator: "A", voted: "C", auth: true},
  297. {validator: "B"},
  298. {validator: "A"}, // Checkpoint block, (don't vote here, it's validated outside of snapshots)
  299. {validator: "B", voted: "C", auth: true},
  300. },
  301. results: []string{"A", "B"},
  302. },
  303. }
  304. // Run through the scenarios and test them
  305. for i, tt := range tests {
  306. // Create the account pool and generate the initial set of validators
  307. accounts := newTesterAccountPool()
  308. validators := make([]common.Address, len(tt.validators))
  309. for j, validator := range tt.validators {
  310. validators[j] = accounts.address(validator)
  311. }
  312. for j := 0; j < len(validators); j++ {
  313. for k := j + 1; k < len(validators); k++ {
  314. if bytes.Compare(validators[j][:], validators[k][:]) > 0 {
  315. validators[j], validators[k] = validators[k], validators[j]
  316. }
  317. }
  318. }
  319. genesis := testutils.Genesis(validators, true)
  320. config := new(istanbul.Config)
  321. *config = *istanbul.DefaultConfig
  322. config.TestQBFTBlock = big.NewInt(0)
  323. if tt.epoch != 0 {
  324. config.Epoch = tt.epoch
  325. }
  326. chain, backend := newBlockchainFromConfig(
  327. genesis,
  328. []*ecdsa.PrivateKey{accounts.accounts[tt.validators[0]]},
  329. config,
  330. )
  331. // Assemble a chain of headers from the cast votes
  332. headers := make([]*types.Header, len(tt.votes))
  333. for j, vote := range tt.votes {
  334. blockNumber := big.NewInt(int64(j) + 1)
  335. headers[j] = &types.Header{
  336. Number: blockNumber,
  337. Time: uint64(int64(j) * int64(config.GetConfig(blockNumber).BlockPeriod)),
  338. Coinbase: accounts.address(vote.validator),
  339. Difficulty: istanbulcommon.DefaultDifficulty,
  340. MixDigest: types.IstanbulDigest,
  341. }
  342. _ = qbftengine.ApplyHeaderQBFTExtra(
  343. headers[j],
  344. qbftengine.WriteValidators(validators),
  345. )
  346. if j > 0 {
  347. headers[j].ParentHash = headers[j-1].Hash()
  348. }
  349. copy(headers[j].Extra, genesis.ExtraData)
  350. if len(vote.voted) > 0 {
  351. if err := accounts.writeValidatorVote(headers[j], vote.validator, vote.voted, vote.auth); err != nil {
  352. t.Errorf("Error writeValidatorVote test: %d, validator: %s, voteType: %v (err=%v)", j, vote.voted, vote.auth, err)
  353. }
  354. }
  355. }
  356. // Pass all the headers through clique and ensure tallying succeeds
  357. head := headers[len(headers)-1]
  358. snap, err := backend.snapshot(chain, head.Number.Uint64(), head.Hash(), headers)
  359. if err != nil {
  360. t.Errorf("test %d: failed to create voting snapshot: %v", i, err)
  361. backend.Stop()
  362. continue
  363. }
  364. // Verify the final list of validators against the expected ones
  365. validators = make([]common.Address, len(tt.results))
  366. for j, validator := range tt.results {
  367. validators[j] = accounts.address(validator)
  368. }
  369. for j := 0; j < len(validators); j++ {
  370. for k := j + 1; k < len(validators); k++ {
  371. if bytes.Compare(validators[j][:], validators[k][:]) > 0 {
  372. validators[j], validators[k] = validators[k], validators[j]
  373. }
  374. }
  375. }
  376. result := snap.validators()
  377. if len(result) != len(validators) {
  378. t.Errorf("test %d: validators mismatch: have %x, want %x", i, result, validators)
  379. backend.Stop()
  380. continue
  381. }
  382. for j := 0; j < len(result); j++ {
  383. if !bytes.Equal(result[j][:], validators[j][:]) {
  384. t.Errorf("test %d, validator %d: validator mismatch: have %x, want %x", i, j, result[j], validators[j])
  385. }
  386. }
  387. backend.Stop()
  388. }
  389. }
  390. func TestSaveAndLoad(t *testing.T) {
  391. snap := &Snapshot{
  392. Epoch: 5,
  393. Number: 10,
  394. Hash: common.HexToHash("1234567890"),
  395. Votes: []*Vote{
  396. {
  397. Validator: common.StringToAddress("1234567891"),
  398. Block: 15,
  399. Address: common.StringToAddress("1234567892"),
  400. Authorize: false,
  401. },
  402. },
  403. Tally: map[common.Address]Tally{
  404. common.StringToAddress("1234567893"): {
  405. Authorize: false,
  406. Votes: 20,
  407. },
  408. },
  409. ValSet: validator.NewSet([]common.Address{
  410. common.StringToAddress("1234567894"),
  411. common.StringToAddress("1234567895"),
  412. }, istanbul.NewRoundRobinProposerPolicy()),
  413. }
  414. db := rawdb.NewMemoryDatabase()
  415. err := snap.store(db)
  416. if err != nil {
  417. t.Errorf("store snapshot failed: %v", err)
  418. }
  419. snap1, err := loadSnapshot(snap.Epoch, db, snap.Hash)
  420. if err != nil {
  421. t.Errorf("load snapshot failed: %v", err)
  422. }
  423. if snap.Epoch != snap1.Epoch {
  424. t.Errorf("epoch mismatch: have %v, want %v", snap1.Epoch, snap.Epoch)
  425. }
  426. if snap.Hash != snap1.Hash {
  427. t.Errorf("hash mismatch: have %v, want %v", snap1.Number, snap.Number)
  428. }
  429. if !reflect.DeepEqual(snap.Votes, snap.Votes) {
  430. t.Errorf("votes mismatch: have %v, want %v", snap1.Votes, snap.Votes)
  431. }
  432. if !reflect.DeepEqual(snap.Tally, snap.Tally) {
  433. t.Errorf("tally mismatch: have %v, want %v", snap1.Tally, snap.Tally)
  434. }
  435. if !reflect.DeepEqual(snap.ValSet, snap.ValSet) {
  436. t.Errorf("validator set mismatch: have %v, want %v", snap1.ValSet, snap.ValSet)
  437. }
  438. }