github.com/core-coin/go-core@v1.1.7/contracts/checkpointoracle/oracle_test.go (about) 1 // Copyright 2019 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package checkpointoracle 18 19 import ( 20 "bytes" 21 "crypto/rand" 22 "encoding/binary" 23 "errors" 24 eddsa "github.com/core-coin/go-goldilocks" 25 "math/big" 26 "reflect" 27 "sort" 28 "testing" 29 "time" 30 31 "github.com/core-coin/go-core/accounts/abi/bind" 32 "github.com/core-coin/go-core/accounts/abi/bind/backends" 33 "github.com/core-coin/go-core/common" 34 "github.com/core-coin/go-core/contracts/checkpointoracle/contract" 35 "github.com/core-coin/go-core/core" 36 "github.com/core-coin/go-core/crypto" 37 "github.com/core-coin/go-core/params" 38 ) 39 40 var ( 41 emptyHash = [32]byte{} 42 43 checkpoint0 = params.TrustedCheckpoint{ 44 SectionIndex: 0, 45 SectionHead: common.HexToHash("0x7fa3c32f996c2bfb41a1a65b3d8ea3e0a33a1674cde43678ad6f4235e764d17d"), 46 CHTRoot: common.HexToHash("0x98fc5d3de23a0fecebad236f6655533c157d26a1aedcd0852a514dc1169e6350"), 47 BloomRoot: common.HexToHash("0x99b5adb52b337fe25e74c1c6d3835b896bd638611b3aebddb2317cce27a3f9fa"), 48 } 49 checkpoint1 = params.TrustedCheckpoint{ 50 SectionIndex: 1, 51 SectionHead: common.HexToHash("0x2d4dee68102125e59b0cc61b176bd89f0d12b3b91cfaf52ef8c2c82fb920c2d2"), 52 CHTRoot: common.HexToHash("0x7d428008ece3b4c4ef5439f071930aad0bb75108d381308df73beadcd01ded95"), 53 BloomRoot: common.HexToHash("0x652571f7736de17e7bbb427ac881474da684c6988a88bf51b10cca9a2ee148f4"), 54 } 55 checkpoint2 = params.TrustedCheckpoint{ 56 SectionIndex: 2, 57 SectionHead: common.HexToHash("0x61c0de578c0115b1dff8ef39aa600588c7c6ecb8a2f102003d7cf4c4146e9291"), 58 CHTRoot: common.HexToHash("0x407a08a407a2bc3838b74ca3eb206903c9c8a186ccf5ef14af07794efff1970b"), 59 BloomRoot: common.HexToHash("0x058b4161f558ce295a92925efc57f34f9210d5a30088d7475c183e0d3e58f5ac"), 60 } 61 ) 62 63 var ( 64 // The block frequency for creating checkpoint(only used in test) 65 sectionSize = big.NewInt(512) 66 67 // The number of confirmations needed to generate a checkpoint(only used in test). 68 processConfirms = big.NewInt(4) 69 ) 70 71 // validateOperation executes the operation, watches and delivers all events fired by the backend and ensures the 72 // correctness by assert function. 73 func validateOperation(t *testing.T, c *contract.CheckpointOracle, backend *backends.SimulatedBackend, operation func(), 74 assert func(<-chan *contract.CheckpointOracleNewCheckpointVote) error, opName string) { 75 // Watch all events and deliver them to assert function 76 var ( 77 sink = make(chan *contract.CheckpointOracleNewCheckpointVote) 78 sub, _ = c.WatchNewCheckpointVote(nil, sink, nil) 79 ) 80 defer func() { 81 // Close all subscribers 82 sub.Unsubscribe() 83 }() 84 operation() 85 86 // flush pending block 87 backend.Commit() 88 if err := assert(sink); err != nil { 89 t.Errorf("operation {%s} failed, err %s", opName, err) 90 } 91 } 92 93 // validateEvents checks that the correct number of contract events 94 // fired by contract backend. 95 func validateEvents(target int, sink interface{}) (bool, []reflect.Value) { 96 chanval := reflect.ValueOf(sink) 97 chantyp := chanval.Type() 98 if chantyp.Kind() != reflect.Chan || chantyp.ChanDir()&reflect.RecvDir == 0 { 99 return false, nil 100 } 101 count := 0 102 var recv []reflect.Value 103 timeout := time.After(1 * time.Second) 104 cases := []reflect.SelectCase{{Chan: chanval, Dir: reflect.SelectRecv}, {Chan: reflect.ValueOf(timeout), Dir: reflect.SelectRecv}} 105 for { 106 chose, v, _ := reflect.Select(cases) 107 if chose == 1 { 108 // Not enough event received 109 return false, nil 110 } 111 count += 1 112 recv = append(recv, v) 113 if count == target { 114 break 115 } 116 } 117 done := time.After(50 * time.Millisecond) 118 cases = cases[:1] 119 cases = append(cases, reflect.SelectCase{Chan: reflect.ValueOf(done), Dir: reflect.SelectRecv}) 120 chose, _, _ := reflect.Select(cases) 121 // If chose equal 0, it means receiving redundant events. 122 return chose == 1, recv 123 } 124 125 func signCheckpoint(addr common.Address, privateKey *eddsa.PrivateKey, index uint64, hash common.Hash) []byte { 126 // CIP 191 style signatures 127 // 128 // Arguments when calculating hash to validate 129 // 1: byte(0x19) - the initial 0x19 byte 130 // 2: byte(0) - the version byte (data with intended validator) 131 // 3: this - the validator address 132 // -- Application specific data 133 // 4 : checkpoint section_index(uint64) 134 // 5 : checkpoint hash (bytes32) 135 // hash = keccak256(checkpoint_index, section_head, cht_root, bloom_root) 136 buf := make([]byte, 8) 137 binary.BigEndian.PutUint64(buf, index) 138 data := append([]byte{0x19, 0x00}, append(addr.Bytes(), append(buf, hash.Bytes()...)...)...) 139 sig, _ := crypto.Sign(crypto.SHA3(data), privateKey) 140 //sig[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 141 return sig 142 } 143 144 // assertSignature verifies whether the recovered signers are equal with expected. 145 func assertSignature(addr common.Address, index uint64, hash [32]byte, r, s [32]byte, v uint8, expect common.Address) bool { 146 buf := make([]byte, 8) 147 binary.BigEndian.PutUint64(buf, index) 148 data := append([]byte{0x19, 0x00}, append(addr.Bytes(), append(buf, hash[:]...)...)...) 149 pubkey, err := crypto.Ecrecover(crypto.SHA3(data), append(r[:], append(s[:], v-27)...)) 150 if err != nil { 151 return false 152 } 153 var signer common.Address 154 copy(signer[:], crypto.SHA3(pubkey)[12:]) 155 return bytes.Equal(signer.Bytes(), expect.Bytes()) 156 } 157 158 type Account struct { 159 key *eddsa.PrivateKey 160 addr common.Address 161 } 162 type Accounts []Account 163 164 func (a Accounts) Len() int { return len(a) } 165 func (a Accounts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 166 func (a Accounts) Less(i, j int) bool { return bytes.Compare(a[i].addr.Bytes(), a[j].addr.Bytes()) < 0 } 167 168 func TestCheckpointRegister(t *testing.T) { 169 t.Skip() 170 // Initialize test accounts 171 var accounts Accounts 172 for i := 0; i < 3; i++ { 173 key, _ := crypto.GenerateKey(rand.Reader) 174 pub := eddsa.Ed448DerivePublicKey(*key) 175 addr := crypto.PubkeyToAddress(pub) 176 accounts = append(accounts, Account{key: key, addr: addr}) 177 } 178 sort.Sort(accounts) 179 180 // Deploy registrar contract 181 contractBackend := backends.NewSimulatedBackend(core.GenesisAlloc{accounts[0].addr: {Balance: big.NewInt(1000000000)}, accounts[1].addr: {Balance: big.NewInt(1000000000)}, accounts[2].addr: {Balance: big.NewInt(1000000000)}}, 10000000) 182 defer contractBackend.Close() 183 184 transactOpts, _ := bind.NewKeyedTransactorWithNetworkID(accounts[0].key, big.NewInt(1337)) 185 186 // 3 trusted signers, threshold 2 187 contractAddr, _, c, err := contract.DeployCheckpointOracle(transactOpts, contractBackend, []common.Address{accounts[0].addr, accounts[1].addr, accounts[2].addr}, sectionSize, processConfirms, big.NewInt(2)) 188 if err != nil { 189 t.Error("Failed to deploy registrar contract", err) 190 } 191 contractBackend.Commit() 192 193 // getRecent returns block height and hash of the head parent. 194 getRecent := func() (*big.Int, common.Hash) { 195 parentNumber := new(big.Int).Sub(contractBackend.Blockchain().CurrentHeader().Number, big.NewInt(1)) 196 parentHash := contractBackend.Blockchain().CurrentHeader().ParentHash 197 return parentNumber, parentHash 198 } 199 // collectSig generates specified number signatures. 200 collectSig := func(index uint64, hash common.Hash, n int, unauthorized *eddsa.PrivateKey) (v []uint8, r [][32]byte, s [][32]byte) { 201 for i := 0; i < n; i++ { 202 _ = signCheckpoint(contractAddr, accounts[i].key, index, hash) 203 if unauthorized != nil { 204 _ = signCheckpoint(contractAddr, unauthorized, index, hash) 205 } 206 //r = append(r, common.BytesToHash(sig[:32])) 207 //s = append(s, common.BytesToHash(sig[32:64])) 208 //v = append(v, sig[64]) 209 } 210 return v, r, s 211 } 212 // insertEmptyBlocks inserts a batch of empty blocks to blockchain. 213 insertEmptyBlocks := func(number int) { 214 for i := 0; i < number; i++ { 215 contractBackend.Commit() 216 } 217 } 218 // assert checks whether the current contract status is same with 219 // the expected. 220 assert := func(index uint64, hash [32]byte, height *big.Int) error { 221 lindex, lhash, lheight, err := c.GetLatestCheckpoint(nil) 222 if err != nil { 223 return err 224 } 225 if lindex != index { 226 return errors.New("latest checkpoint index mismatch") 227 } 228 if !bytes.Equal(lhash[:], hash[:]) { 229 return errors.New("latest checkpoint hash mismatch") 230 } 231 if lheight.Cmp(height) != 0 { 232 return errors.New("latest checkpoint height mismatch") 233 } 234 return nil 235 } 236 237 // Test future checkpoint registration 238 validateOperation(t, c, contractBackend, func() { 239 number, hash := getRecent() 240 v, r, s := collectSig(0, checkpoint0.Hash(), 2, nil) 241 c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) 242 }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { 243 return assert(0, emptyHash, big.NewInt(0)) 244 }, "test future checkpoint registration") 245 246 insertEmptyBlocks(int(sectionSize.Uint64() + processConfirms.Uint64())) 247 248 // Test transaction replay protection 249 validateOperation(t, c, contractBackend, func() { 250 number, _ := getRecent() 251 v, r, s := collectSig(0, checkpoint0.Hash(), 2, nil) 252 hash := common.HexToHash("deadbeef") 253 c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) 254 }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { 255 return assert(0, emptyHash, big.NewInt(0)) 256 }, "test transaction replay protection") 257 258 // Test unauthorized signature checking 259 validateOperation(t, c, contractBackend, func() { 260 number, hash := getRecent() 261 u, _ := crypto.GenerateKey(rand.Reader) 262 v, r, s := collectSig(0, checkpoint0.Hash(), 2, u) 263 c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) 264 }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { 265 return assert(0, emptyHash, big.NewInt(0)) 266 }, "test unauthorized signature checking") 267 268 // Test un-multi-signature checkpoint registration 269 validateOperation(t, c, contractBackend, func() { 270 number, hash := getRecent() 271 v, r, s := collectSig(0, checkpoint0.Hash(), 1, nil) 272 c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) 273 }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { 274 return assert(0, emptyHash, big.NewInt(0)) 275 }, "test un-multi-signature checkpoint registration") 276 277 // Test valid checkpoint registration 278 validateOperation(t, c, contractBackend, func() { 279 number, hash := getRecent() 280 v, r, s := collectSig(0, checkpoint0.Hash(), 2, nil) 281 c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) 282 }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { 283 if valid, recv := validateEvents(2, events); !valid { 284 return errors.New("receive incorrect number of events") 285 } else { 286 for i := 0; i < len(recv); i++ { 287 event := recv[i].Interface().(*contract.CheckpointOracleNewCheckpointVote) 288 if !assertSignature(contractAddr, event.Index, event.CheckpointHash, event.R, event.S, event.V, accounts[i].addr) { 289 return errors.New("recover signer failed") 290 } 291 } 292 } 293 number, _ := getRecent() 294 return assert(0, checkpoint0.Hash(), number.Add(number, big.NewInt(1))) 295 }, "test valid checkpoint registration") 296 297 distance := 3*sectionSize.Uint64() + processConfirms.Uint64() - contractBackend.Blockchain().CurrentHeader().Number.Uint64() 298 insertEmptyBlocks(int(distance)) 299 300 // Test uncontinuous checkpoint registration 301 validateOperation(t, c, contractBackend, func() { 302 number, hash := getRecent() 303 v, r, s := collectSig(2, checkpoint2.Hash(), 2, nil) 304 c.SetCheckpoint(transactOpts, number, hash, checkpoint2.Hash(), 2, v, r, s) 305 }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { 306 if valid, recv := validateEvents(2, events); !valid { 307 return errors.New("receive incorrect number of events") 308 } else { 309 for i := 0; i < len(recv); i++ { 310 event := recv[i].Interface().(*contract.CheckpointOracleNewCheckpointVote) 311 if !assertSignature(contractAddr, event.Index, event.CheckpointHash, event.R, event.S, event.V, accounts[i].addr) { 312 return errors.New("recover signer failed") 313 } 314 } 315 } 316 number, _ := getRecent() 317 return assert(2, checkpoint2.Hash(), number.Add(number, big.NewInt(1))) 318 }, "test uncontinuous checkpoint registration") 319 320 // Test old checkpoint registration 321 validateOperation(t, c, contractBackend, func() { 322 number, hash := getRecent() 323 v, r, s := collectSig(1, checkpoint1.Hash(), 2, nil) 324 c.SetCheckpoint(transactOpts, number, hash, checkpoint1.Hash(), 1, v, r, s) 325 }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { 326 number, _ := getRecent() 327 return assert(2, checkpoint2.Hash(), number) 328 }, "test uncontinuous checkpoint registration") 329 330 // Test stale checkpoint registration 331 validateOperation(t, c, contractBackend, func() { 332 number, hash := getRecent() 333 v, r, s := collectSig(2, checkpoint2.Hash(), 2, nil) 334 c.SetCheckpoint(transactOpts, number, hash, checkpoint2.Hash(), 2, v, r, s) 335 }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { 336 number, _ := getRecent() 337 return assert(2, checkpoint2.Hash(), number.Sub(number, big.NewInt(1))) 338 }, "test stale checkpoint registration") 339 }