github.com/theQRL/go-zond@v0.2.1/zondclient/gzondclient/gzondclient_test.go (about) 1 // Copyright 2021 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 17 package gzondclient 18 19 import ( 20 "bytes" 21 "context" 22 "encoding/json" 23 "math/big" 24 "testing" 25 26 "github.com/theQRL/go-zond" 27 "github.com/theQRL/go-zond/common" 28 "github.com/theQRL/go-zond/consensus/beacon" 29 "github.com/theQRL/go-zond/core" 30 "github.com/theQRL/go-zond/core/types" 31 "github.com/theQRL/go-zond/crypto" 32 "github.com/theQRL/go-zond/crypto/pqcrypto" 33 "github.com/theQRL/go-zond/node" 34 "github.com/theQRL/go-zond/params" 35 "github.com/theQRL/go-zond/rpc" 36 zondsvc "github.com/theQRL/go-zond/zond" 37 "github.com/theQRL/go-zond/zond/filters" 38 "github.com/theQRL/go-zond/zond/zondconfig" 39 "github.com/theQRL/go-zond/zondclient" 40 ) 41 42 var ( 43 testKey, _ = pqcrypto.HexToDilithium("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 44 testAddr = testKey.GetAddress() 45 zeroAddr, _ = common.NewAddressFromString("Z0000000000000000000000000000000000000000") 46 testContract, _ = common.NewAddressFromString("Z000000000000000000000000000000000000beef") 47 testEmpty, _ = common.NewAddressFromString("Z000000000000000000000000000000000000eeee") 48 testSlot = common.HexToHash("0xdeadbeef") 49 testValue = crypto.Keccak256Hash(testSlot[:]) 50 testBalance = big.NewInt(2e15) 51 ) 52 53 func newTestBackend(t *testing.T) (*node.Node, []*types.Block) { 54 // Generate test chain. 55 genesis, blocks := generateTestChain() 56 // Create node 57 n, err := node.New(&node.Config{}) 58 if err != nil { 59 t.Fatalf("can't create new node: %v", err) 60 } 61 // Create Zond Service 62 config := &zondconfig.Config{Genesis: genesis} 63 zondservice, err := zondsvc.New(n, config) 64 if err != nil { 65 t.Fatalf("can't create new zond service: %v", err) 66 } 67 filterSystem := filters.NewFilterSystem(zondservice.APIBackend, filters.Config{}) 68 n.RegisterAPIs([]rpc.API{{ 69 Namespace: "zond", 70 Service: filters.NewFilterAPI(filterSystem), 71 }}) 72 73 // Import the test chain. 74 if err := n.Start(); err != nil { 75 t.Fatalf("can't start test node: %v", err) 76 } 77 if _, err := zondservice.BlockChain().InsertChain(blocks[1:]); err != nil { 78 t.Fatalf("can't import test blocks: %v", err) 79 } 80 return n, blocks 81 } 82 83 func generateTestChain() (*core.Genesis, []*types.Block) { 84 genesis := &core.Genesis{ 85 Config: params.AllBeaconProtocolChanges, 86 Alloc: core.GenesisAlloc{ 87 testAddr: {Balance: testBalance, Storage: map[common.Hash]common.Hash{testSlot: testValue}}, 88 testContract: {Nonce: 1, Code: []byte{0x13, 0x37}}, 89 testEmpty: {Balance: big.NewInt(1)}, 90 }, 91 ExtraData: []byte("test genesis"), 92 Timestamp: 9000, 93 } 94 generate := func(i int, g *core.BlockGen) { 95 g.OffsetTime(5) 96 g.SetExtra([]byte("test")) 97 } 98 _, blocks, _ := core.GenerateChainWithGenesis(genesis, beacon.NewFaker(), 1, generate) 99 blocks = append([]*types.Block{genesis.ToBlock()}, blocks...) 100 return genesis, blocks 101 } 102 103 func TestGzondClient(t *testing.T) { 104 backend, _ := newTestBackend(t) 105 client := backend.Attach() 106 defer backend.Close() 107 defer client.Close() 108 109 tests := []struct { 110 name string 111 test func(t *testing.T) 112 }{ 113 { 114 "TestGetProof1", 115 func(t *testing.T) { testGetProof(t, client, testAddr) }, 116 }, 117 { 118 "TestGetProof2", 119 func(t *testing.T) { testGetProof(t, client, testContract) }, 120 }, 121 { 122 "TestGetProofEmpty", 123 func(t *testing.T) { testGetProof(t, client, testEmpty) }, 124 }, 125 { 126 "TestGetProofNonExistent", 127 func(t *testing.T) { testGetProofNonExistent(t, client) }, 128 }, 129 { 130 "TestGetProofCanonicalizeKeys", 131 func(t *testing.T) { testGetProofCanonicalizeKeys(t, client) }, 132 }, 133 { 134 "TestGCStats", 135 func(t *testing.T) { testGCStats(t, client) }, 136 }, 137 { 138 "TestMemStats", 139 func(t *testing.T) { testMemStats(t, client) }, 140 }, 141 { 142 "TestGetNodeInfo", 143 func(t *testing.T) { testGetNodeInfo(t, client) }, 144 }, 145 { 146 "TestSubscribePendingTxHashes", 147 func(t *testing.T) { testSubscribePendingTransactions(t, client) }, 148 }, 149 { 150 "TestSubscribePendingTxs", 151 func(t *testing.T) { testSubscribeFullPendingTransactions(t, client) }, 152 }, 153 { 154 "TestCallContract", 155 func(t *testing.T) { testCallContract(t, client) }, 156 }, 157 { 158 "TestCallContractWithBlockOverrides", 159 func(t *testing.T) { testCallContractWithBlockOverrides(t, client) }, 160 }, 161 // The testaccesslist is a bit time-sensitive: the newTestBackend imports 162 // one block. The `testAccessList` fails if the miner has not yet created a 163 // new pending-block after the import event. 164 // Hence: this test should be last, execute the tests serially. 165 { 166 "TestAccessList", 167 func(t *testing.T) { testAccessList(t, client) }, 168 }, 169 { 170 "TestSetHead", 171 func(t *testing.T) { testSetHead(t, client) }, 172 }, 173 } 174 for _, tt := range tests { 175 t.Run(tt.name, tt.test) 176 } 177 } 178 179 func testAccessList(t *testing.T, client *rpc.Client) { 180 zc := New(client) 181 // Test transfer 182 msg := zond.CallMsg{ 183 From: testAddr, 184 To: &common.Address{}, 185 Gas: 21000, 186 GasFeeCap: big.NewInt(1000000000), 187 Value: big.NewInt(1), 188 } 189 al, gas, vmErr, err := zc.CreateAccessList(context.Background(), msg) 190 if err != nil { 191 t.Fatalf("unexpected error: %v", err) 192 } 193 if vmErr != "" { 194 t.Fatalf("unexpected vm error: %v", vmErr) 195 } 196 if gas != 21000 { 197 t.Fatalf("unexpected gas used: %v", gas) 198 } 199 if len(*al) != 0 { 200 t.Fatalf("unexpected length of accesslist: %v", len(*al)) 201 } 202 // Test reverting transaction 203 msg = zond.CallMsg{ 204 From: testAddr, 205 To: nil, 206 Gas: 100000, 207 GasFeeCap: big.NewInt(1000000000), 208 Value: big.NewInt(1), 209 Data: common.FromHex("0x608060806080608155fd"), 210 } 211 al, gas, vmErr, err = zc.CreateAccessList(context.Background(), msg) 212 if err != nil { 213 t.Fatalf("unexpected error: %v", err) 214 } 215 if vmErr == "" { 216 t.Fatalf("wanted vmErr, got none") 217 } 218 if gas == 21000 { 219 t.Fatalf("unexpected gas used: %v", gas) 220 } 221 if len(*al) != 1 || al.StorageKeys() != 1 { 222 t.Fatalf("unexpected length of accesslist: %v", len(*al)) 223 } 224 // address changes between calls, so we can't test for it. 225 if (*al)[0].Address == zeroAddr { 226 t.Fatalf("unexpected address: %v", (*al)[0].Address) 227 } 228 if (*al)[0].StorageKeys[0] != common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000081") { 229 t.Fatalf("unexpected storage key: %v", (*al)[0].StorageKeys[0]) 230 } 231 } 232 233 func testGetProof(t *testing.T, client *rpc.Client, addr common.Address) { 234 zc := New(client) 235 zondcl := zondclient.NewClient(client) 236 result, err := zc.GetProof(context.Background(), addr, []string{testSlot.String()}, nil) 237 if err != nil { 238 t.Fatal(err) 239 } 240 if result.Address != addr { 241 t.Fatalf("unexpected address, have: %v want: %v", result.Address, addr) 242 } 243 // test nonce 244 if nonce, _ := zondcl.NonceAt(context.Background(), result.Address, nil); result.Nonce != nonce { 245 t.Fatalf("invalid nonce, want: %v got: %v", nonce, result.Nonce) 246 } 247 // test balance 248 if balance, _ := zondcl.BalanceAt(context.Background(), result.Address, nil); result.Balance.Cmp(balance) != 0 { 249 t.Fatalf("invalid balance, want: %v got: %v", balance, result.Balance) 250 } 251 252 // test storage 253 if len(result.StorageProof) != 1 { 254 t.Fatalf("invalid storage proof, want 1 proof, got %v proof(s)", len(result.StorageProof)) 255 } 256 for _, proof := range result.StorageProof { 257 if proof.Key != testSlot.String() { 258 t.Fatalf("invalid storage proof key, want: %q, got: %q", testSlot.String(), proof.Key) 259 } 260 slotValue, _ := zondcl.StorageAt(context.Background(), addr, common.HexToHash(proof.Key), nil) 261 if have, want := common.BigToHash(proof.Value), common.BytesToHash(slotValue); have != want { 262 t.Fatalf("addr %x, invalid storage proof value: have: %v, want: %v", addr, have, want) 263 } 264 } 265 // test code 266 code, _ := zondcl.CodeAt(context.Background(), addr, nil) 267 if have, want := result.CodeHash, crypto.Keccak256Hash(code); have != want { 268 t.Fatalf("codehash wrong, have %v want %v ", have, want) 269 } 270 } 271 272 func testGetProofCanonicalizeKeys(t *testing.T, client *rpc.Client) { 273 zc := New(client) 274 275 // Tests with non-canon input for storage keys. 276 // Here we check that the storage key is canonicalized. 277 result, err := zc.GetProof(context.Background(), testAddr, []string{"0x0dEadbeef"}, nil) 278 if err != nil { 279 t.Fatal(err) 280 } 281 if result.StorageProof[0].Key != "0xdeadbeef" { 282 t.Fatalf("wrong storage key encoding in proof: %q", result.StorageProof[0].Key) 283 } 284 if result, err = zc.GetProof(context.Background(), testAddr, []string{"0x000deadbeef"}, nil); err != nil { 285 t.Fatal(err) 286 } 287 if result.StorageProof[0].Key != "0xdeadbeef" { 288 t.Fatalf("wrong storage key encoding in proof: %q", result.StorageProof[0].Key) 289 } 290 291 // If the requested storage key is 32 bytes long, it will be returned as is. 292 hashSizedKey := "0x00000000000000000000000000000000000000000000000000000000deadbeef" 293 result, err = zc.GetProof(context.Background(), testAddr, []string{hashSizedKey}, nil) 294 if err != nil { 295 t.Fatal(err) 296 } 297 if result.StorageProof[0].Key != hashSizedKey { 298 t.Fatalf("wrong storage key encoding in proof: %q", result.StorageProof[0].Key) 299 } 300 } 301 302 func testGetProofNonExistent(t *testing.T, client *rpc.Client) { 303 addr, _ := common.NewAddressFromString("Z0000000000000000000000000000000000000001") 304 ec := New(client) 305 result, err := ec.GetProof(context.Background(), addr, nil, nil) 306 if err != nil { 307 t.Fatal(err) 308 } 309 if result.Address != addr { 310 t.Fatalf("unexpected address, have: %v want: %v", result.Address, addr) 311 } 312 // test nonce 313 if result.Nonce != 0 { 314 t.Fatalf("invalid nonce, want: %v got: %v", 0, result.Nonce) 315 } 316 // test balance 317 if result.Balance.Sign() != 0 { 318 t.Fatalf("invalid balance, want: %v got: %v", 0, result.Balance) 319 } 320 // test storage 321 if have := len(result.StorageProof); have != 0 { 322 t.Fatalf("invalid storage proof, want 0 proof, got %v proof(s)", have) 323 } 324 // test codeHash 325 if have, want := result.CodeHash, (common.Hash{}); have != want { 326 t.Fatalf("codehash wrong, have %v want %v ", have, want) 327 } 328 // test codeHash 329 if have, want := result.StorageHash, (common.Hash{}); have != want { 330 t.Fatalf("storagehash wrong, have %v want %v ", have, want) 331 } 332 } 333 334 func testGCStats(t *testing.T, client *rpc.Client) { 335 zc := New(client) 336 _, err := zc.GCStats(context.Background()) 337 if err != nil { 338 t.Fatal(err) 339 } 340 } 341 342 func testMemStats(t *testing.T, client *rpc.Client) { 343 zc := New(client) 344 stats, err := zc.MemStats(context.Background()) 345 if err != nil { 346 t.Fatal(err) 347 } 348 if stats.Alloc == 0 { 349 t.Fatal("Invalid mem stats retrieved") 350 } 351 } 352 353 func testGetNodeInfo(t *testing.T, client *rpc.Client) { 354 zc := New(client) 355 info, err := zc.GetNodeInfo(context.Background()) 356 if err != nil { 357 t.Fatal(err) 358 } 359 360 if info.Name == "" { 361 t.Fatal("Invalid node info retrieved") 362 } 363 } 364 365 func testSetHead(t *testing.T, client *rpc.Client) { 366 zc := New(client) 367 err := zc.SetHead(context.Background(), big.NewInt(0)) 368 if err != nil { 369 t.Fatal(err) 370 } 371 } 372 373 func testSubscribePendingTransactions(t *testing.T, client *rpc.Client) { 374 zc := New(client) 375 zondcl := zondclient.NewClient(client) 376 // Subscribe to Transactions 377 ch := make(chan common.Hash) 378 zc.SubscribePendingTransactions(context.Background(), ch) 379 // Send a transaction 380 chainID, err := zondcl.ChainID(context.Background()) 381 if err != nil { 382 t.Fatal(err) 383 } 384 // Create transaction 385 tx := types.NewTx(&types.DynamicFeeTx{ 386 Nonce: 0, 387 To: &common.Address{1}, 388 Value: big.NewInt(1), 389 Gas: 22000, 390 GasFeeCap: big.NewInt(1), 391 Data: nil, 392 }) 393 signer := types.LatestSignerForChainID(chainID) 394 signedTx, err := types.SignTx(tx, signer, testKey) 395 if err != nil { 396 t.Fatal(err) 397 } 398 // Send transaction 399 err = zondcl.SendTransaction(context.Background(), signedTx) 400 if err != nil { 401 t.Fatal(err) 402 } 403 // Check that the transaction was sent over the channel 404 hash := <-ch 405 if hash != signedTx.Hash() { 406 t.Fatalf("Invalid tx hash received, got %v, want %v", hash, signedTx.Hash()) 407 } 408 } 409 410 func testSubscribeFullPendingTransactions(t *testing.T, client *rpc.Client) { 411 zc := New(client) 412 zondcl := zondclient.NewClient(client) 413 // Subscribe to Transactions 414 ch := make(chan *types.Transaction) 415 zc.SubscribeFullPendingTransactions(context.Background(), ch) 416 // Send a transaction 417 chainID, err := zondcl.ChainID(context.Background()) 418 if err != nil { 419 t.Fatal(err) 420 } 421 // Create transaction 422 tx := types.NewTx(&types.DynamicFeeTx{ 423 Nonce: 1, 424 To: &common.Address{1}, 425 Value: big.NewInt(1), 426 Gas: 22000, 427 GasFeeCap: big.NewInt(1), 428 Data: nil, 429 }) 430 signer := types.LatestSignerForChainID(chainID) 431 signedTx, err := types.SignTx(tx, signer, testKey) 432 if err != nil { 433 t.Fatal(err) 434 } 435 // Send transaction 436 err = zondcl.SendTransaction(context.Background(), signedTx) 437 if err != nil { 438 t.Fatal(err) 439 } 440 // Check that the transaction was sent over the channel 441 tx = <-ch 442 if tx.Hash() != signedTx.Hash() { 443 t.Fatalf("Invalid tx hash received, got %v, want %v", tx.Hash(), signedTx.Hash()) 444 } 445 } 446 447 func testCallContract(t *testing.T, client *rpc.Client) { 448 zc := New(client) 449 msg := zond.CallMsg{ 450 From: testAddr, 451 To: &common.Address{}, 452 Gas: 21000, 453 GasFeeCap: big.NewInt(1000000000), 454 Value: big.NewInt(1), 455 } 456 // CallContract without override 457 if _, err := zc.CallContract(context.Background(), msg, big.NewInt(0), nil); err != nil { 458 t.Fatalf("unexpected error: %v", err) 459 } 460 // CallContract with override 461 override := OverrideAccount{ 462 Nonce: 1, 463 } 464 mapAcc := make(map[common.Address]OverrideAccount) 465 mapAcc[testAddr] = override 466 if _, err := zc.CallContract(context.Background(), msg, big.NewInt(0), &mapAcc); err != nil { 467 t.Fatalf("unexpected error: %v", err) 468 } 469 } 470 471 func TestOverrideAccountMarshal(t *testing.T) { 472 om := map[common.Address]OverrideAccount{ 473 {0x11}: { 474 // Zero-valued nonce is not overridden, but simply dropped by the encoder. 475 Nonce: 0, 476 }, 477 {0xaa}: { 478 Nonce: 5, 479 }, 480 {0xbb}: { 481 Code: []byte{1}, 482 }, 483 {0xcc}: { 484 // 'code', 'balance', 'state' should be set when input is 485 // a non-nil but empty value. 486 Code: []byte{}, 487 Balance: big.NewInt(0), 488 State: map[common.Hash]common.Hash{}, 489 // For 'stateDiff' the behavior is different, empty map 490 // is ignored because it makes no difference. 491 StateDiff: map[common.Hash]common.Hash{}, 492 }, 493 } 494 495 marshalled, err := json.MarshalIndent(&om, "", " ") 496 if err != nil { 497 t.Fatalf("unexpected error: %v", err) 498 } 499 500 expected := `{ 501 "Z1100000000000000000000000000000000000000": {}, 502 "Zaa00000000000000000000000000000000000000": { 503 "nonce": "0x5" 504 }, 505 "Zbb00000000000000000000000000000000000000": { 506 "code": "0x01" 507 }, 508 "Zcc00000000000000000000000000000000000000": { 509 "code": "0x", 510 "balance": "0x0", 511 "state": {} 512 } 513 }` 514 515 if string(marshalled) != expected { 516 t.Error("wrong output:", string(marshalled)) 517 t.Error("want:", expected) 518 } 519 } 520 521 func TestBlockOverridesMarshal(t *testing.T) { 522 coinbase, _ := common.NewAddressFromString("Z1111111111111111111111111111111111111111") 523 524 for i, tt := range []struct { 525 bo BlockOverrides 526 want string 527 }{ 528 { 529 bo: BlockOverrides{}, 530 want: `{}`, 531 }, 532 { 533 bo: BlockOverrides{ 534 Coinbase: coinbase, 535 }, 536 want: `{"coinbase":"Z1111111111111111111111111111111111111111"}`, 537 }, 538 { 539 bo: BlockOverrides{ 540 Number: big.NewInt(1), 541 Time: 3, 542 GasLimit: 4, 543 BaseFee: big.NewInt(5), 544 }, 545 want: `{"number":"0x1","time":"0x3","gasLimit":"0x4","baseFee":"0x5"}`, 546 }, 547 } { 548 marshalled, err := json.Marshal(&tt.bo) 549 if err != nil { 550 t.Fatalf("unexpected error: %v", err) 551 } 552 if string(marshalled) != tt.want { 553 t.Errorf("Testcase #%d failed. expected\n%s\ngot\n%s", i, tt.want, string(marshalled)) 554 } 555 } 556 } 557 558 func testCallContractWithBlockOverrides(t *testing.T, client *rpc.Client) { 559 zc := New(client) 560 msg := zond.CallMsg{ 561 From: testAddr, 562 To: &common.Address{}, 563 Gas: 50000, 564 GasFeeCap: big.NewInt(1000000000), 565 Value: big.NewInt(1), 566 } 567 override := OverrideAccount{ 568 // Returns coinbase address. 569 Code: common.FromHex("0x41806000526014600cf3"), 570 } 571 mapAcc := make(map[common.Address]OverrideAccount) 572 mapAcc[common.Address{}] = override 573 res, err := zc.CallContract(context.Background(), msg, big.NewInt(0), &mapAcc) 574 if err != nil { 575 t.Fatalf("unexpected error: %v", err) 576 } 577 if !bytes.Equal(res, common.FromHex("0x0000000000000000000000000000000000000000")) { 578 t.Fatalf("unexpected result: %x", res) 579 } 580 581 // Now test with block overrides 582 coinbase, _ := common.NewAddressFromString("Z1111111111111111111111111111111111111111") 583 bo := BlockOverrides{ 584 Coinbase: coinbase, 585 } 586 res, err = zc.CallContractWithBlockOverrides(context.Background(), msg, big.NewInt(0), &mapAcc, bo) 587 if err != nil { 588 t.Fatalf("unexpected error: %v", err) 589 } 590 if !bytes.Equal(res, common.FromHex("0x1111111111111111111111111111111111111111")) { 591 t.Fatalf("unexpected result: %x", res) 592 } 593 }